拦截器
// axios 拦截器
axios.interceptors.request.use(
(config) => {
if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers['user-token'] = store.state.token;
} else if (window.sessionStorage.getItem('token')) {
store.commit('SET_TOKEN', window.sessionStorage.getItem('token'))
config.headers['user-token'] = window.sessionStorage.getItem('token')
} else {
router.replace({
//path: '/login'
})
}
return config;
},
err => {
return Promise.reject(err);
});
axios.interceptors.response.use(
response => {
if (response.status != 200) {
return Promise.reject("err state:" + response.status) // 返回接口返回的错误信息
}
if (response.data.status == 0) {
store.commit('CLEAR_TOKEN');
store.commit('CLEAR_USERINFO')
router.replace({
path: '/login'
})
}
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// 返回 401 清除token信息并跳转到登录页面
store.commit('CLEAR_TOKEN');
router.replace({
path: '/login'
})
}
return Promise.reject(error.response.data)
}
return Promise.reject(error) // 返回接口返回的错误信息
});
取消请求
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get(url, {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
//handle error
}
});
//取消请求(信息的参数可以设置的)
source.cancel("操作被用户取消");
网友评论