/*在没登录完之前所有的请求全部取消,登录成功后把取消的请求列表重新发起*/
import axios from 'axios';
const whiteList = ['post /api/login'];
const resetFetchList = [];
let isLogin = false;
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
// console.log(config);
const requestMark = `${config.method} ${config.url}`; // 请求标识 为了在响应的时候删除请求队列中的数据
const flag = resetFetchList.findIndex(item=>item.requestMark === requestMark);
if (flag !== -1) {
// resetFetchList[flag].cancel(); // 删除重复请求时用
resetFetchList.splice(flag,1); // 在等待重新发起的请求列表中移除
}
const cancelToken = axios.CancelToken;
const source = cancelToken.source();
config.cancelToken = source.token;
config.cancel = source.cancel;
config.requestMark = requestMark; //添加唯一标识符
if (!whiteList.includes(requestMark) && !isLogin) {
resetFetchList.push(config);
config.cancel();
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
if(response.config.requestMark === 'post /api/login' /** 并且登录成功 */) {
isLogin = true;
resetFetchList.forEach(item => {
axios.request(item);
})
}
// console.log(currentFetchList);
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default axios;
axios 请求取消及重发
最新推荐文章于 2024-04-19 14:25:39 发布