axios 请求中断和请求重试 [复制链接]
发表于 2024-9-5 15:08:21 | 显示全部楼层 |阅读模式
请求中断​

请求已经发出去了,怎样取消掉这个已经发出去的请求?
   微信扫码体验一下 (说不定哪天你就用得上)
  

用途
   

  • 比如取消正在下载中的文件
  • 点击差别的下拉框选项,向服务器发送新请求但携带差别的参数,响应回来的数据在折线图内里展示。每次请求的数据量较大,但着实只要渲染最后一次选择。
  • 应用场景迁移,一样平常在数据量较大的情况下,可通过请求中断,节流网络资源
  做法
  1. 通过 AbortController 中断请求
复制代码
  1. <script setup lang="ts">
  2. import axios from 'axios'
  3. import { ref } from 'vue'
  4. const progress = ref(0) // 进度条百分比
  5. let controller: AbortController // 中止控制器
  6. // 中止下载
  7. const abortDownload = () => {
  8.   if (controller) {
  9.     controller.abort() // 使用 abort 方法中止下载
  10.     console.log('中止下载')
  11.   }
  12. }
  13. // 下载视频
  14. const fetchVideo = () => {
  15.   controller = new AbortController() // 创建 AbortController
  16.   axios({
  17.     // 将中止控制器传递给 axios 的 get 方法
  18.     method: 'GET',
  19.     url: 'http://localhost:3000/video',
  20.     signal: controller.signal,
  21.     responseType: 'arraybuffer',
  22.     onDownloadProgress: (progressEvent) => {
  23.       // 计算进度百分比
  24.       progress.value = Math.round((progressEvent.loaded / progressEvent.total!) * 100)
  25.     }
  26.   })
  27.     .then((response) => {
  28.       console.log('下载完成', response)
  29.       // ✅ 保存下载的文件
  30.       const { buffer } = new Uint8Array(response.data)
  31.       const blob = new Blob([buffer], { type: 'application/octet-stream' })
  32.       const link = document.createElement('a') // 创建链接元素
  33.       link.href = URL.createObjectURL(blob) // 将 Blob 对象转换为 URL
  34.       link.download = 'video.mp4' // 设置文件名
  35.       link.click() // 模拟点击链接元素
  36.     })
  37.     .catch((err) => {
  38.       if (axios.isCancel(err)) {
  39.         console.log('下载被取消')
  40.       } else if (err.name === 'AbortError') {
  41.         console.log('下载被中止')
  42.       } else {
  43.         console.error(`下载错误:${err.message}`)
  44.       }
  45.     })
  46. }
  47. </script>
  48. <template>
  49.   <div>
  50.     <button class="download" @click="fetchVideo">下载视频</button>
  51.     <button class="abort" @click="abortDownload">中止下载</button>
  52.     <div class="progress-bar">
  53.       <div class="progress" :style="{ width: progress + '%' }"></div>
  54.       {{ progress }}%
  55.     </div>
  56.   </div>
  57. </template>
  58. <style scoped>
  59. .progress-bar {
  60.   height: 20px;
  61.   background-color: #eee;
  62.   margin-top: 10px;
  63. }
  64. .progress {
  65.   width: 0%;
  66.   height: 100%;
  67.   background-color: #4caf50;
  68.   transition: width 0.2s linear;
  69. }
  70. </style>
复制代码
请求重试

拓展一个插件 axios-retry 插件
1 .axios-retry 1.6k 插件可以更方便实现请求重试。
2. 配置 axios-retry 核心属性
  1. <script setup lang="ts">
  2. import axios from 'axios'
  3. import axiosRetry from 'axios-retry'
  4. const request = axios.create({
  5.   baseURL: 'http://localhost:3000',
  6.   timeout: 2000,
  7. })
  8. // axios-retry 插件
  9. axiosRetry(request, {
  10.   retries: 3, // 设置重试次数
  11.   retryDelay: () => 500, // 设置重试延迟时间
  12.   shouldResetTimeout: true, // 重置请求超时时间
  13.   retryCondition: (error) => ['ECONNABORTED', 'ERR_NETWORK'].includes(error.code!), // 重试条件
  14. })
  15. // 请求中止控制器
  16. let controller: AbortController
  17. // --- 获取数据 ---
  18. const getData = async () => {
  19.   // 请求控制器
  20.   controller = new AbortController()
  21.   const res = await request({
  22.     method: 'GET',
  23.     url: '/delay_3s_data',
  24.     signal: controller.signal, // 添加请求中止标识
  25.   })
  26.   console.log('成功获取数据', res)
  27. }
  28. const stop = () => {
  29.   // 中止网络请求
  30.   controller.abort()
  31. }
  32. </script>
  33. <template>
  34.   <h1>axios请求重试-axiosRetry</h1>
  35.   <button @click="getData()">发送请求</button>
  36.   <button @click="stop()">中止请求</button>
  37. </template>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

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

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表