取消请求

取消请求

在 axios 调用中设置 timeout 属性可处理与 响应 相关的超时。

在某些情况下(例如网络连接变得不可用),axios 调用将受益于提前取消 连接。 如果不取消,axios 调用可能会挂起,直到父代码/堆栈超时(在服务器端应用程序中可能是几分钟)。

要终止 axios 调用,你可以使用以下方法:

结合 timeout 和取消方法(例如 signal)应该涵盖 响应 相关超时和 连接 相关超时。

signal: AbortController

v0.22.0 开始 axios 支持 AbortController 以 fetch API 方式取消请求:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

使用最新的 AbortSignal.timeout() API [nodejs 17.3+] 的超时示例:

axios.get('/foo/bar', {
   signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds
}).then(function(response) {
   //...
});

使用超时辅助函数的示例:

function newAbortSignal(timeoutMs) {
  const abortController = new AbortController();
  setTimeout(() => abortController.abort(), timeoutMs || 0);

  return abortController.signal;
}

axios.get('/foo/bar', {
   signal: newAbortSignal(5000) //Aborts request after 5 seconds
}).then(function(response) {
   //...
});

CancelToken deprecated

你还可以使用 CancelToken 取消请求。

axios 取消令牌 API 是基于撤回的 可撤销的 promise 提案

此 API 自 v0.22.0 起已弃用,不应在新项目中使用

你可以使用 CancelToken.source 工厂创建取消令牌,如下所示:

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.');

你还可以通过将执行函数传递给 CancelToken 构造函数来创建取消令牌:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

注意: 你可以使用相同的取消令牌/信号取消多个请求。

在过渡期间,你可以使用两种取消 API,即使是针对同一个请求:

const controller = new AbortController();

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token,
  signal: controller.signal
}).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.');
// OR
controller.abort(); // the message parameter is not supported