axios基本使用和拦截器使用
- axios与fetch()、ajax一样都是交互工具。Axios是一个基于
promise
的node的http
库,可以用在浏览器和node.js中。
axios的基本使用
- .get()方法
axios.get('http://127.0.0.1:3000/axios-get/Bill', {
params: {id: 'Bill'} // 还可以使用url?key=value 或者 url/xx(Restful模式,和后台配合)
}).then(res => {
console.log(res.data);
})
- .post()方法
axios.post('http://127.0.0.1:3000/axios-post', {
userName: 'Bill',
pwd: '123'
}).then(res => {
console.log(res.data);
})
这里需要注意,后台需要用插件接收,比如说我是node用的body-parser配置下接收json格式的就可以了。
- 还有其他的PUT类似POST、DELETE类似GET。
拦截器
- Request拦截器
一定要注意要return否者设置不成功
axios.interceptors.request.use(config => {
config.headers.token = 'hello'; // 设置请求头为例,跨域当然需要后台设置下token
// console.log(config); // 打印出所有可设置config选项
return config; // !!!一定要返回,否则不生效
}, err => {
console.log(err);
})
- Response拦截器
一定要注意要return否者设置不成功
axios.interceptors.response.use(res => {
// 返回最终axios处理的数据
return res.data; // 一定要返回,否则不生效
}, err => {
console.log(err);
})
实例:
// 响应拦截器
axios.interceptors.response.use(res => {
// 返回最终axios处理的数据
return res.data; // 一定要返回,否则不生效
}, err => {
console.log(err);
})
axios.post('http://127.0.0.1:3000/axios-int').then(res => {
console.log(res); // 我这里拿到的就是上面return的data结果了
})
less talking, more working —— noob!