Axios拦截器是什么?
对每一次的请求和响应进行拦截之后进行相应的处理。
请求拦截器,你可以在发送请求体之前在请求体里加上token,然后我们的调接口可以省略传token,然后避免了代码的重复。
响应拦截器,接收到响应之后的一些操作,比如可以进行request中异常处理
创建axios实例
// 创建一个axios实例
improt axios from 'axios'
const request = axios.creste({
baseURL: http://localhost:8888,
timeout: 50000,
responseType: "json",
withCredentials: true, // 跨域请求是否要携带cookie
headers: {
'Content-Type': 'application-json/x-www-form-urlencoded;charset=utf-8',
}
})
请求拦截器
request.interceptors.request.use( config => {
//在发送请求之前做的一些操作,例如加上token这些
.......
return config
}, error => {
//对请求错误做些什么
return Promise.reject(error)
})
响应拦截器
request.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
});
如果你稍后需要移除拦截器,可以这样
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);