axios取消哀求

打印 上一主题 下一主题

主题 987|帖子 987|积分 2961

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
 1.使用CancelToken:

  1. class RequestHttp {
  2.         service: AxiosInstance;
  3.         public constructor(config: AxiosRequestConfig) {
  4.                 // 实例化axios
  5.                 this.service = axios.create(config);
  6.                 /**
  7.                  * @description 请求拦截器
  8.                  * 客户端发送请求 -> [请求拦截器] -> 服务器
  9.                  */
  10.                 this.service.interceptors.request.use(
  11.                         (config: any) => {
  12.                                 if (!getUrlParams("id")) {
  13.                                         config["cancelToken"] = new axios.CancelToken(function (cancel) {
  14.                                                 cancel("当前URL中未携带id参数,请求已被取消");
  15.                                         });
  16.                                 }
  17.                                 return config;
  18.                         },
  19.                         (error: AxiosError) => {
  20.                                 return Promise.reject(error);
  21.                         }
  22.                 );
  23.         }
  24. }
  25. export default new RequestHttp(config);
复制代码
2.使用AbortController

  1. class RequestHttp {
  2.         service: AxiosInstance;
  3.         public constructor(config: AxiosRequestConfig) {
  4.                 // 实例化axios
  5.                 this.service = axios.create(config);
  6.                 /**
  7.                  * @description 请求拦截器
  8.                  * 客户端发送请求 -> [请求拦截器] -> 服务器
  9.                  */
  10.                 this.service.interceptors.request.use(
  11.                         (config: any) => {
  12.                                 if (!getUrlParams("id")) {
  13.                                         const abortController = new AbortController();
  14.                                         config.signal = abortController.signal;
  15.                                         abortController.abort("当前URL中未携带id参数,请求已被取消");
  16.                                 }
  17.                                 return config;
  18.                         },
  19.                         (error: AxiosError) => {
  20.                                 return Promise.reject(error);
  21.                         }
  22.                 );
  23.         }
  24. }
  25. export default new RequestHttp(config);
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

何小豆儿在此

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表