axios文档:https://www.axios-http.cn/docs/intro
let pendingList = []
service.interceptors.request.use(
config => {
// 中断重复请求
if(pendingList.includes(config.url)){
config.cancelToken = new axios.CancelToken((cancel) => {
// cancel 函数的参数会作为 promise 的 error 被捕获
cancel(`重复的请求被主动拦截: ${config.url}`);
});
}else{
pendingList.push(config.url)
}
if (store.getters.token) {
config.headers['X-Token'] = ''
}
return config
},
error => {
return Promise.reject(error)
}
)
// respone拦截器
service.interceptors.response.use(
response => {
// 已经完成的请求,从待完成列表中去掉
const pendingIndex = pendingList.indexOf(response.config.url)
pendingList.splice(pendingIndex, 1)
const res = response.data
if (res.status && res.status !== 200) {
// 登录超时,重新登录
if (res.status === 401) {
store.dispatch('FedLogOut').then(() => {
location.reload()
})
}
return Promise.reject(res || 'error')
} else {
return Promise.resolve(res)
}
},
error => {
Message.error({
message: '网络错误,请稍后重试'
})
// console.log('err' + error) // for debug
return Promise.reject(error)
}
)