Axios拦截器的使用
拦截器
- 拦截器(interceptors)用来全局拦截axios的每一次请求与响应
- 好处:可以把每个请求中,某些重复性的业务代码封装到拦截器中,提高代码的复用性
1.请求拦截器--请求发起前执行
axios.defaults.baseURL = "http://www.xxx.top:3009";
axios.interceptors.request.use(function (config) {
// 此处可进行返回之前的一系列操作
// 注入token、检查、打开进度条等
return config
},function (error) {
return Promise.reject(error)
})
// attention:必须return
2.响应拦截器
axios.interceptors.response.use(function (response) {
//成功进入第一个参数
return response.data // 因为axios默认加了一层壳, 脱壳数据,方便后期操作
},function (error) {
//失败进入第二个参数
return Promise.reject(error)
})