Axios
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
服务器端
使用json-server
1. axios基本使用
// 1.GETaxios({ method: 'GET', url: 'http://localhost:3000/posts/2'}).then(res => { console.log(res);})// POSTaxios({ method: 'POST', url: 'http://localhost:3000/posts', data: { title: 'test', author: 'lll' }}).then(res => { console.log(res);})// PUTaxios({ method: 'PUT', url: 'http://localhost:3000/posts/3', data: { title: 'test', author: 'new-lll' }}).then(res => { console.log(res);})// DELETEaxios({ method: 'DELETE', url: 'http://localhost:3000/posts/3',}).then(res => { console.log(res);})
2. 其他请求方法
axios.request(config)axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])// requestaxios.request({ method: 'GET', url: 'http://localhost:3000/posts/2'}).then(res => { console.log(res)})// POSTaxios.post( 'http://localhost:3000/comments', { "body": "other", "postId": 2 }).then(res => { console.log(res)})
3. axios默认配置
// default settingaxios.defaults.method = 'GET'axios.defaults.baseURL = 'http:localhost:3000'axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
4. axios创建实例对象
// 创建实例对象const obj = axios.create({ baseURL: 'http://localhost:3000'})// obj实例和axios对象几乎相同obj({ url: 'posts/2'}).then(res => { console.log(res)})
5. axios拦截器
/** * 拦截器实质是函数 * 请求拦截器,在请求发出时检查请求的参数等是否正确 * 响应拦截器,在接受响应前,对响应进行预处理*/// 请求拦截器axios.interceptors.request.use(functio(config) { console.log('req success') return config}), function (error) { console.log('req fail') return Promise.reject(error)}// 接收拦截器axios.interceptors.response.use(functio(response) { console.log('res success') return response;}, function (error) { console.log('res fail') return Promise.reject(error);});
6. 取消请求
let cancel = nulbtns[0].onclick = function () { // 检查上一个请求是否结束 if (cancel !== null) { cancel() } axios({ url: '/posts', cancelToken: new axios.CancelTok(function executor(c) { cancel = c; }) }).then(res => { cancel = null console.log(res) })btns[1].onclick = function () { cancel()}