/* 取消请求设置 */
const CancelToken = axios.CancelToken;
let pendList = [];
/**
* 移除重复请求
* @param {Object} config 请求配置对象
*/
function removePending(config) {
for (let p of pendList) {
let currentPend = createInterceptUrl(config); //本次请求信息
let historyPend = config.url.includes(axios.defaults.baseURL) ? axios.defaults.baseURL + p.u : p.u; //历史请求信息(请求的config.url中不包含baseUrl,但响应中的url会包含baseUrl,此处先处理两者差异)
let isMatch = currentPend === historyPend; //是否匹配
if (isMatch) {
let index = pendList.indexOf(p);
p.f('取消请求'); //执行取消操作
index > -1 && pendList.splice(index, 1);
return;
}
}
}
/**
* 延迟请求,相同请求不得在短时间内重复发送
* @param {Array} reqList - 请求缓存列表
* @param {String} url - 当前请求地址
*/
function delayRepeatRequest(config) {
setTimeout(() => {
removePending(config);
}, 500);
}
/**
* 创建用于拦截请求的标识,为保证请求信息完整,组合了请求的地址、类型、参数
* @param {Object} config axios请求的配置对象
* @returns {String} 返回用于拦截的字符串标识
*/
function createInterceptUrl(config) {
return config.url + '&' + config.method + '&' + qs.stringify(config.params) + '&' + qs.stringify(config.data);
}
/* 请求拦截 */
axios.interceptors.request.use(
config => {
removePending(config); //在一个axios发送前执行一下取消操作
/* 创建取消请求的token,并把本次请求的信息添加到请求列表 */
config.cancelToken = new CancelToken(c => {
pendList.push({
u: createInterceptUrl(config),
f: c
});
});
return config;
},
error => {
return Promise.error(error);
}
);
/* 响应拦截 */
axios.interceptors.response.use(
response => {
delayRepeatRequest(response.config); //在一个axios响应后再执行一下取消操作,把已经完成的请求从pendList中移除
return response.status === 200 ? Promise.resolve(response) : Promise.reject(response); //状态码为200接口访问成功,其他抛出错误
},
error => {
//axios.isCancel(error); //验证是否是取消请求的错误
return Promise.reject(error);
}
);
vue项目axios拦截重复请求
最新推荐文章于 2025-05-07 19:59:53 发布
本文介绍了一种在使用Axios库进行HTTP请求时,避免重复请求的方法。通过创建请求标识,存储并检查每个请求,确保相同的请求不会在短时间内被多次发送,有效提高了应用的性能。

1501

被折叠的 条评论
为什么被折叠?



