当前位置: 移动技术网 > 移动技术>移动开发>IOS > axios取消上次重复请求

axios取消上次重复请求

2020年07月08日  | 移动技术网移动技术  | 我要评论

转载

原文地址忘了,当时是随手搜的问题

基于axios

utils/request.ts

let pending: any[] = []; // 声明一个数组用于存储每个请求的取消函数和axios标识
let cancelToken = axios.CancelToken;
let removePending = (config: any) => {
  for (let p in pending) {
    // 当前请求在数组中存在时执行函数体
    if (pending[p].u === `${config.url} ${JSON.stringify(config.data)}&${config.method}`) { 
      pending[p].f(); //执行取消操作
      pending.splice(Number(p), 1);
    }
  }
}

//请求拦截器
req.interceptors.request.use((request: any) => {
  // 取消重复请求
  removePending(request); // 在一个axios发送前执行一下取消操作
  request.cancelToken = new cancelToken((c) => {
    // 这里的axios标识我是用请求地址&请求方式拼接的字符串
    pending.push({ u: `${request.url} ${JSON.stringify(request.data)}&${request.method}`, f: c 		});
  });
  return request
});

// 响应拦截器
req.interceptors.response.use(
 (response: any) => {
   // 已结束请求删除
   removePending(response.config);
   return response
 },

本文地址:https://blog.csdn.net/jx950915/article/details/107165120

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网