一篇文章教你学会如何取消接口请求

385 阅读2分钟

前提

需要对 axios 或 promise 有一定的了解或基础,才能更好的理解以下内容的解释。若是零基础也没事,可以跟随文章逐步了解💪

axios

中文官网:www.axios-http.cn

什么是 axios?Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js。Axios 使用简单,包的尺寸小且提供了易于扩展的接口。通俗一点就是,前后端数据交互的方式或桥梁。

安装

npm install axios

如何取消请求?

axios 的版本必须大于等于 0.22.0 才支持使用 AbortController 取消请求

运用场景:

  • 多次请求,取消前面的请求
  • 离开页面取消请求
  • 根据业务情况主动取消请求
  • ...

AbortController

AbortController 是Web API的一部分,用于控制一个或多个Web请求的中断。它通过signal属性与请求关联,并通过调用abort()方法来终止请求。AbortController的优势在于其简单性和与原生fetch API的兼容性。

代码示例:

// 1、创建 AbortController 实例
const controller = new AbortController();
const { signal } = controller;

// 2、发起请求并传递 signal
axios.get('/your-endpoint', { signal })
  .then(response => {
    // 处理响应
    console.log(response);
  })
  .catch(error => {
    if (axios.isCancel(error)) { // 使用 axios.isCancel() 判断是否是人为取消请求
      console.log('Request canceled', error.message);
    } else {
      // 处理其他错误
      console.error('An error occurred:', error);
    }
  });

// 3、在需要取消请求时调用 abort()
controller.abort();

AbortController 与 CancelToken

这时,肯定会有人问,CancelToken 也可以取消请求,两者的区别是什么?为什么推荐使用 AbortController?最主要的就是在 v0.22.0 版本中 CancelToken 已经被废弃了,不再维护和支持使用,最好使用 AbortController 来取消请求。

CancelToken 官方示例:

若想详细了解 CancelToken 可以到官网学习

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 {
    // handle error
  }
});

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

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');