main.js文件添加如下配置:
Vue.prototype.$axios = axios
添加请求拦截
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Authorization')) {
console.log("Authorization is true")
config.headers.token = localStorage.getItem('Authorization');// 在发送的请求的header上添加token
}
return config;
},
error => {
console.log("Authorization is false")
return Promise.reject(error);
});
// 添加响应拦截
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
if (error.response) {
switch (error.response.status) {
case 401:
// 返回 401 清除token信息并跳转到登录页面
commit(SET_LOGINTOKEN,"未授权,请登录");
case 400:
// 返回 401 清除token信息并跳转到登录页面
commit(SET_LOGINTOKEN,"请求错误");
case 403:
// 返回 401 清除token信息并跳转到登录页面
commit(SET_LOGINTOKEN,"拒绝访问");
}
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath}
})
}
return Promise.reject(error.response.data)
});
然后在VUEX里面用axios发送请求,如下:
axios.post(userApiurl,data).then(response =>{});
踩坑: main.js里面的配置不变,在vuex中没有直接使用axios,而是用axios创建了一个其他对象,如下:
const axiosInstance = axios.create({
headers:{'Content-Type':'application/json'},
// 设置传输内容的类型和编码
withCredentials:true // 指定某个请求应该发送凭据
});
再用axiosInstance发送请求的话,main.js里面axios配置没有在这些请求上生效