乐闻世界logo
搜索文章和话题

How to cancel/abort ajax request in axios

1个答案

1

Canceling or aborting an AJAX request in Axios can be achieved using the CancelToken provided by Axios. The CancelToken enables you to cancel an AJAX request. Here are the steps and examples for using CancelToken:

Steps to Use CancelToken:

  1. Create a cancel token: Use the axios.CancelToken factory function to create a cancel token.

  2. Pass the cancel token to the request configuration: When initiating the request, include this cancel token as part of the request configuration object.

  3. Cancel the request: Use the cancellation function (cancel) obtained when creating the token to cancel the request.

Example Code:

javascript
import axios from 'axios'; // Step 1: Create cancel token const CancelToken = axios.CancelToken; let cancel; // Step 2: Initiate request and pass cancel token axios.get('/some/path', { cancelToken: new CancelToken(function executor(c) { // This executor function receives a cancellation function as a parameter cancel = c; }) }) .then(response => { // Handle response }) .catch(error => { // Handle error if (axios.isCancel(error)) { console.log('Request canceled:', error.message); } else { // Handle other errors } }); // Step 3: Cancel request // Call the cancel function when needed to cancel the request cancel('Operation canceled by the user.');

In this example, we create a cancel token and pass it to axios.get when initiating the request. When the cancel function is executed, if the request is not yet completed, it will be canceled, and the catch block will capture an axios.Cancel error.

Another Approach: Using CancelToken.source Factory Method

Another way to create a cancel token is by using the CancelToken.source method:

javascript
import axios from 'axios'; // Create cancel token source const source = axios.CancelToken.source(); // Initiate request and pass cancel token axios.get('/some/path', { cancelToken: source.token }) .then(response => { // Handle response }) .catch(error => { // Handle error if (axios.isCancel(error)) { console.log('Request canceled:', error.message); } }); // Cancel request source.cancel('Operation canceled by the user.');

In this example, we use CancelToken.source to create an object that includes a token for the request configuration and a cancel method for canceling the request. This approach is more concise and easier to understand.

Notes:

  • Canceling a request is an uncommon operation, typically used when navigating away from a page or unmounting a component to cancel pending requests and avoid unnecessary resource wastage.
  • After canceling a request, Axios throws an error. You must check in the catch block using the axios.isCancel function to determine if the error is due to cancellation, ensuring proper handling.
2024年6月29日 12:07 回复

你的答案