How To Cancel a Request in JavaScript
Several methods of front-end web page cancellation request
When working with web applications, there may be times when we need to cancel a request that is being sent to the server. This can happen for various reasons, such as the user changing their mind or the network is slow. In such cases, it is important to be able to cancel the request to avoid wasting resources and prevent unwanted actions on the server. In this article, we will discuss how to cancel the request in JavaScript.
Canceling a Request with XMLHttpRequest
The most common way to send requests in JavaScript is through the XMLHttpRequest
(XHR) object. This object provides a way to send HTTP or HTTPS requests and receive responses asynchronously. To cancel a request that is being sent with XMLHttpRequest
, we can use the abort()
method of the object.
The abort()
method immediately stops the request and sets the readyState
property to 0
. This means that the onreadystatechange
event will not be fired, and the onload
and onerror
events will not be fired either. And it fires the abort
event, Here is an example:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/1.json');
xhr.send();
xhr.addEventListener('error', console.error);
xhr.addEventListener('onload', console.log);
xhr.addEventListener('abort', console.warn);
// Cancel the request after 1seconds
// setTimeout(() => {
xhr.abort();
// }, 1000);
In this example, We set a timeout of 1 second and call the abort()
method on the XMLHttpRequest
object. This will cancel the request if it has not been completed within 1 second. In Devtools we get the data of abort
event:
Canceling a Request with fetch()
The fetch()
API is a modern way to send HTTP or HTTPS requests in JavaScript. It provides a simpler and more flexible interface than XMLHttpRequest
. To cancel a request that is being sent with fetch()
, we can use the AbortController
interface.
The AbortController
interface provides a way to cancel fetch requests by calling its abort()
method. We can create a new AbortController
object and pass it to the signal
option of the fetch()
method. Then, when we want to cancel the request, we can call the abort()
method of the AbortController
object. Here is an example:
const controller = new AbortController();
const signal = controller.signal;
fetch('/data.json', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Cancel the request after 3 seconds
setTimeout(() => {
controller.abort();
}, 3000);
In this example, we create a new AbortController
object and pass its signal
property as the second argument to the fetch()
method. We then make a GET request to https://example.com/data.json
and handle the response as JSON data. If an error occurs, we log it to the console.
We also set a timeout of 3 seconds and call the abort()
method on the AbortController
object. This will cancel the request if it has not completed within 3 seconds. Here’s the error returned when we cancel:
But please note that AbortController
can only be used once, which means that if you have already called controller.abort()
, it will be an error to pass it to fetch
again:
Canceling a Request with Axios
Axios is a popular library for making HTTP requests in JavaScript. It provides an easy-to-use interface and supports many features, such as request and response interception, automatic retries, and more. To cancel a request that is being sent with Axios, we can use the CancelToken
feature.
The CancelToken
feature provides a way to cancel Axios requests by creating a new CancelToken
object and passing it to the cancelToken
option of the Axios request configuration object. Then, when we want to cancel the request, we can call the cancel()
method of the CancelToken
object.
Here is an example of how to use the CancelToken
feature to cancel a request with Axios:
import axios from 'axios';
const source = axios.CancelToken.source();
axios.get('/data.json', { cancelToken: source.token })
.then(response => console.log(response.data))
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
console.error(error);
}
});
// Cancel the request after 3 seconds
setTimeout(() => {
source.cancel('Request canceled due to timeout');
}, 3000);
But this method is marked as deprecated in v0.22.0
, although you can still use it, it is not recommended for new projects. The latest way is similar to fetch:
const controller = new AbortController();
axios
.get('/data.json', {
signal: controller.signal,
})
.then(
(response) => {
//...
},
(err) => {
// Built-in method to judge whether it is a cancellation error
const isCancel = axios.isCancel(err); // true
console.error(err);
}
);
// cancel the request
controller.abort();
AbortSignal.timeout()
When you really need timeout cancellation, you can simply use AbortSignal.timeout()
. It returns an AbortSignal
which will automatically abort after the specified time. The following is used in fetch and in Axios:
// === fetch ===
fetch('/data.json', { signal: AbortSignal.timeout(1000) })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
// === axios ===
axios
.get('/data.json', {
signal: AbortSignal.timeout(1000),
})
.then(
(response) => {
//...
},
(err) => {
const isCancel = axios.isCancel(err); // true
console.error(err);
}
);
Conclusion
Canceling requests can help prevent unnecessary network traffic and server load, and improve the overall performance and user experience of a web application. Hope this article is helpful to you.
Thanks for reading, catch you in the next one, cheers.
Not a Medium member? Support me here by becoming one.