封装axios请求重试和路由切换时请求取消

请求重试函数:这里注意两个变量__retryCount 和retry分别代表当前次数和重试次数。如果请求中没有配置retry则正常进行不会进行重试。

javascript 复制代码
// 请求重试
async function requestAgainSend(
  err: AxiosError<any, any> & newConfig,
  axios: AxiosInstance,
) {
  const config: AxiosRequestConfig & newConfig = err.config || {};
  if (!config || !config.retry) {
    return Promise.reject(err);
  }
  config.__retryCount = config.__retryCount || 0;
  // 判断是否超过
  if (config.__retryCount >= config.retry) {
    return Promise.reject(err);
  }
  // 重试次数
  config.__retryCount += 1;
  // 延时处理
  const backoff = new Promise(function (resolve) {
    setTimeout(function () {
      resolve("success");
    }, 1000);
  });
  await backoff;
  return await axios(config);
}

请求取消我这里的场景是路由切换时,将上次路由全部取消也可以配置部分取消。注意变量noCancel,他来控制那些不需要被取消。

回顾axios请求取消的几种使用方式:1. 第一种使用AbortController

javascript 复制代码
const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// 取消请求
controller.abort()

第二种:

javascript 复制代码
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理错误
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

我是用的是第三种:

javascript 复制代码
const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});

// 取消请求
cancel();

思路:全局维护一个函数集合,其中每一项为cancel(),在请求拦截中添加此函数到集合中,在beforeEach中执行每一个函数并清空集合。

javascript 复制代码
// 在pinia中维护集合和方法,方便调用
import { defineStore } from "pinia";

export const requestStore = defineStore("request", () => {
  const cancelReqList = ref([]);
  const addCancelReq = (cancel: any) => {
    const maxCancelTokenNum = 30; // 最大存cancelToken条数
    if (cancelReqList.value.length >= maxCancelTokenNum) {
      cancelReqList.value.shift();
    }
    cancelReqList.value.push(cancel);
  };
  const removeCancelReq = (index: any) => {
    cancelReqList.value.splice(index, 1);
  };
  return { cancelReqList, addCancelReq, removeCancelReq };
});



// 请求拦截中添加取消函数
service.interceptors.request.use(
  (config: any) => {
    if (!config.noCancel) {
      config.cancelToken = new axios.CancelToken((c) => {
        requestStore().addCancelReq(c);
      });
    }
    
  },
  (err: AxiosError<any, any>) => {
    return Promise.reject(err);
  },
);


// 在router beforeEach路由切换时依次执行。
router.beforeEach(async (to, form, next) => {
  ...
  const { cancelReqList, removeCancelReq } = requestStore();
  cancelReqList.forEach((cancel, index) => {
    cancel();
    removeCancelReq(index);
  });
});

出现的问题

类似这种错误报名你取消请求成功了,但是error的结构不再是以前的结构了

if (error instanceof axios.Cancel) return;

相关推荐
花海如潮淹2 分钟前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux
都叫我大帅哥1 小时前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
_丿丨丨_5 小时前
XSS(跨站脚本攻击)
前端·网络·xss
天天进步20155 小时前
前端安全指南:防御XSS与CSRF攻击
前端·安全·xss
Dcs5 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
拾光拾趣录7 小时前
括号生成算法
前端·算法
fouryears_234177 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes