• axios 或 fetch 如何实现对发出的请求的终止?


    终止 HTTP 请求是一个重要的功能,特别是在需要优化性能、避免不必要的请求或在某些事件发生时(例如用户点击取消)中断正在进行的请求时。以下是如何使用 axiosfetch 实现请求终止的方法:

    1. axios

    axios 使用了 CancelToken 来支持取消请求。

    以下是使用 axios 取消请求的例子:

    const axios = require('axios');
    
    // 创建一个 CancelToken 的源
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    
    axios.get('https://api.example.com/data', {
      cancelToken: source.token
    }).catch(function(thrown) {
      if (axios.isCancel(thrown)) {
        console.log('Request canceled', thrown.message);
      } else {
        // 处理其他错误
      }
    });
    
    // 在需要时取消请求
    source.cancel('Operation canceled by the user.');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2. fetch

    对于原生的 fetch API,你可以使用 AbortControllersignal 属性来取消请求。

    以下是使用 fetch 取消请求的示例:

    const controller = new AbortController();
    const signal = controller.signal;
    
    fetch('https://api.example.com/data', { signal })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => {
        if (err.name === 'AbortError') {
          console.log('Fetch aborted');
        } else {
          console.error('Fetch error: ', err);
        }
      });
    
    // 在需要时取消请求
    controller.abort();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    这里,AbortController 和它的 signalfetch 请求相关联。当调用 controller.abort() 时,与该 signal 关联的 fetch 请求将被中断。

    总的来说,不论是使用 axios 还是 fetch,都提供了取消正在进行的 HTTP 请求的能力。这在某些场景下(例如页面卸载或用户取消操作时)能够避免不必要的后续操作或错误处理

  • 相关阅读:
    io+day5
    带你一起玩转Java流
    SpringBoot 异步使用@Async原理及线程池配置
    新版H5大圣牛牛十三幺游戏网站源码+搭建教程+支持透视+座位控+防反杀
    springboot整合其它项目
    又一款机器学习模型解释神器:LIME
    【MyBatis】代码生成
    挂载硬盘相关操作-linux004
    TypeChat、JSONSchemaChat实战 - 让ChatGPT更听你的话
    【 Vue 】Diff 算法上
  • 原文地址:https://blog.csdn.net/weixin_43850639/article/details/132598662