Middle+
How can an HTTP request be canceled?
sobes.tech AI
Answer from AI
Cancelling an HTTP request depends on the APIs used, but in modern browsers and frontend frameworks, the following approaches are most commonly used:
- AbortController (Fetch API):
An
AbortControllerobject is created, and its signal is passed in the fetch options. Later,abort()can be called to cancel the request.
const controller = new AbortController();
fetch('https://example.com/data', { signal: controller.signal })
.then(response => response.json())
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request cancelled');
} else {
console.error('Error:', err);
}
});
// Cancel the request
controller.abort();
-
XMLHttpRequest: You can call the
xhr.abort()method to cancel the request. -
Libraries (e.g., Axios): They provide their own cancellation methods, often based on AbortController or custom cancellation tokens.
Thus, to cancel a request, you need to have a reference to the controller or request object and call the appropriate cancellation method.