import axios from 'axios';
// req拦截
axios.interceptors.request.use(
//设置头部的token config.headers['tokens'] = 55555
let token = localStorage.getItem('token')
config => {
if (token === null) { // 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.Authorization = `${token}`;
}
return config;
},
err => {
return Promise.reject(err);
});
// res拦截
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response.code === ) {
// 返回 401 跳转到登录页面
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath}
})
}
return Promise.reject(error.response.msg) // 返回接口返回的错误信息
});
PS: 建议把拦截器独立到一个js文件,然后在引入。详细了解请点击