当前位置: 首页 > news >正文

axios之CancelToken取消请求

从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController 取消请求

此 API 从 v0.22.0 开始已被弃用,不应在新项目中使用

官网链接

1. 背景

最近项目中遇到一个场景,当连续触发一个请求时,如果是同一个接口,则保留最后一次的请求,之前的请求取消。

查阅了下axios文档,有一个属性CancelToken,把这个添加到axios配置中

 

2. 使用

1:在request时,添加cancelToken

  request: [(config: AxiosRequestConfig) => {const cacheKey = `${config.method}${config.url}`if (config.autoCancel) {removeCache(cacheKey)}config.cancelToken = new axios.CancelToken((c) => {caches[cacheKey] = c})return config},(error: any) => Promise.reject(error),],

2:在reponse时,删除key

  response: [(res: AxiosResponse) => {const cacheKey = `${res.config.method}${res.config.url}`if (res.config.autoCancel) {removeCache(cacheKey)}return res},(error: any) => Promise.reject(error),],

3:判断是否存在重复请求

const caches: Record<string, Canceler> = {}
function removeCache(key: string) {if (caches[key]) {caches[key]()delete caches[key]}
}

这里的autoCancel是为了解决url相同,请求参数不同时,自定义添加的,具体请求方式可以根据这个值来决定是否开启cancelToken

3. 全部代码

/*** 通过取消重复请求解决请求“竞态”问题* - 如何定义“重复”:method和url相同*/
import axios, { AxiosRequestConfig, Canceler, AxiosResponse } from 'axios'const caches: Record<string, Canceler> = {}
function removeCache(key: string) {if (caches[key]) {caches[key]()delete caches[key]}
}const cancelInterceptors = {request: [(config: AxiosRequestConfig) => {const cacheKey = `${config.method}${config.url}`if (config.autoCancel) {removeCache(cacheKey)}config.cancelToken = new axios.CancelToken((c) => {caches[cacheKey] = c})return config},(error: any) => Promise.reject(error),],response: [(res: AxiosResponse) => {const cacheKey = `${res.config.method}${res.config.url}`if (res.config.autoCancel) {removeCache(cacheKey)}return res},(error: any) => Promise.reject(error),],
}export default cancelInterceptors

在封装的axios里面添加配置

// 往request请求中添加配置
service.interceptors.request.use(...cancelInterceptors.request)// 往response请求中添加配置
service.interceptors.response.use(...cancelInterceptors.response)

在response失败error中axios返回了一个失败状态axios.isCancel(error)

(error: AxiosError) => {// if (axios.isCancel(error) && error.message === SCRM_CANCEL_MESSAGE) {//   // 被手动取消的数据统计接口,不展示提示if (axios.isCancel(error)) {// 被取消的接口,不展示提示} else {message.error(error.response?.statusText || error.message || '网络错误')}// 网络层面错误,如接口地址写错了会走到这里return Promise.reject(error)}

3. 原理

source file:axios/lib/adapters/xhr.js

1:创建请求

var request = new XMLHttpRequest()if (config.cancelToken) {// Handle cancellationconfig.cancelToken.promise.then(function onCanceled(cancel) {if (!request) {return;}request.abort();reject(cancel);// Clean up requestrequest = null;});
}

2:创建新的取消

在source file:axios/lib/cancel/CancelToken.js

  var token = this;executor(function cancel(message) {if (token.reason) {// Cancellation has already been requestedreturn;}token.reason = new Cancel(message);resolvePromise(token.reason);});
}

2:取消请求

 在axios/lib/adapters/xhr.js文件中取消request.abort();请求,

if (config.cancelToken) {// Handle cancellationconfig.cancelToken.promise.then(function onCanceled(cancel) {if (!request) {return;}request.abort();reject(cancel);// Clean up requestrequest = null;});}

笔记 

http://www.lryc.cn/news/386289.html

相关文章:

  • Unity | API鉴权用到的函数汇总
  • 【python】socket通信代码解析
  • FastGPT 手动部署错误:MongooseServerSelectionError: getaddrinfo EAI_AGAIN mongo
  • 用英文介绍芝加哥(1):Making Modern Chicago Part 1 Building a Boomtown
  • 【启明智显分享】低成本RISC-V工业级HMI方案推荐
  • 深入探索STM32的SPI功能:W25Q64 Flash存储器全攻略
  • 【SQL Server数据库】带函数查询和综合查询(1)
  • 使用WebService接口进行数据通信
  • AI进阶指南第五课,大模型相关概念(知识库,微调)
  • 【深度学习基础】`view` 和 `reshape` 的参数详解
  • 【笔记】Spring Cloud Gateway 实现 gRPC 代理
  • 云顶之弈数据网站
  • Linux(Ubuntu)下源码开发整个流程完成版本(下载->编译->模拟器运行)
  • el-form表单实现校验
  • 一台TrinityCore服务器客户端连接网速慢(未解决)
  • [系统运维|Xshell]宿主机无法连接上NAT网络下的虚拟机进行维护?主机ping不通NAT网络下的虚拟机,虚拟机ping的通主机!解决办法
  • C 语言实例 - 查找数组中最大的元素值
  • MySQL之可扩展性(七)
  • 微服务框架中Nacos的个人学习心得
  • Unity Animator 运行时修改某个动画状态的播放速度
  • 阿里云常用的操作
  • 【MATLAB源码-第231期】基于matlab的polar码编码译码仿真,对比SC,SCL,BP,SCAN,SSC等译码算法误码率。
  • 创新实训(十三) 项目开发——实现用户终止对话功能
  • 基于Java+MySQL停车场车位管理系统详细设计和实现(源码+LW+调试文档+讲解等)
  • LeetCode 53.最大子数组和(dp)
  • IOS17闪退问题Assertion failure in void _UIGraphicsBeginImageContextWithOptions
  • float8格式
  • 云效BizDevOps上手亲测
  • 亚太杯赛题思路发布(中文版)
  • 【Linux】部署 GitLab 服务