Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

There are often requirements to cancel the request in the project, such as cancel the request after the timeout of 30 seconds, cancel the request of the previous page when jumping to a new page, users manually cancel the request and other functions, these scenarios need to cancel the request. Take a look at axios/fetch/XMLHttpRequest request, how to cancel the request.

axios

There are two main ways to cancel a request in AXIos: using the canceltoken.source () factory function and the CancelToken constructor. Both methods can cancel a request, one for multiple requests and one for a single request.

Next, we use the canceltoken. source factory function to cancel the request

The same cancelToken can cancel multiple requests at the same time

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

axios.get('/user/12345', {
  cancelToken: source.token
}).then((data) = > console.log(data))
  .catch((error) = > {
    // Determine whether to manually cancel
    if (axios.isCancel(thrown)) {
      console.log('Request was manually cancelled:', error.message);
    } else {
      // Other request errors were processed}}); axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// Manually cancel the request. The parameter is optional. (GET - /user/12345 and POST - /user/12345 will be cancelled requests)
source.cancel('User manually cancels request');
Copy the code

The CancelToken constructor creates the CancelToken

The CancelToken constructor can be used to generate a separate CancelToken for each request to cancel an individual request

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken((c) = > {
    The CancelToken argument is a callback function that returns the CancelToken in the function
    cancel = c;
  })
}).then((data) = > console.log(data))
  .catch((error) = > {
    // Determine whether to manually cancel
    if (axios.isCancel(thrown)) {
      console.log('Request was manually cancelled:', error.message);
    } else {
      // Other request errors were processed}});// Cancel the request
cancel();
Copy the code

fetch

In the fetch requests, you need to use to create a new AbortController object, to cancel the request, the object has a signal properties, signal into the fetch request configuration, and then we use AbortController abort method can cancel the request.

const controller = new AbortController();
const { signal } = controller;

fetch("/user/12345", { signal }).then(response= > {
    console.log('Request successful');
}).catch(err= > {
  if(err.name === "AbortError") {
		// The request was cancelled manually
	} else {
    // Processing error}});setTimeout(() = > {
  // Cancel the request manually
  controller.abort();
}, 1000)
Copy the code

XMLHttpRequest

When making a request with XMLHttpRequest, abort() aborts the request, readyState changes to xmlHttpreques.unsent, and the status status code changes to 0

const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "/user/12345";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  if(xhr.readyState === XMLHttpRequest.UNSENT) {
    if (status === 0) {
			// The request was cancelled}}else if(xhr.readyState === XMLHttpRequest.DONE) {
    var status = xhr.status;
    if (status === 0 || (status >= 200 && status < 400)) {
      // The request succeeded
      console.log(xhr.responseText);
    } else {
      // Processing error}}else if 
};
xhr.send();

setTimeout(() = > {
  // Cancel the request manually
  xhr.abort();
}, 1000)
Copy the code

conclusion

Whether through axios/fetch/XMLHttpRequest which way to send the request, cancel methods are generally similar, is to call the abort () method, and then determine whether in the error correction for manual request.