When making a request using axios, there are two ways to cancel the request:
- Cancel request with CancelToken instance
You can cancel the request by creating a CancelToken instance and passing it into the requested config object. Then, where you need to cancel the request, you can call the cancel method to send a cancel request signal.
Here is an example:
import axios from 'axios'; const source = (); const fetchData = async () => { try { const res = await ('/some/url', { cancelToken: }); (); } catch (error) { if ((error)) { ('Request canceled:', ); } else { (error); } } }; // Cancel the request at some point('Operation canceled by the user.');
In the above code, we first create a CancelToken instance named source and pass it into the requested config object. Then, at the location where the request needs to be cancelled, we send the cancel request signal by calling the () method. If the request has been canceled, an error containing the reason for the cancellation is thrown and you can check for this error in the catch block and handle it.
- Cancel the request through the cancel attribute
Another way is to set the cancel property directly on the request object, which is a function. When you need to cancel the request, just call this function.
Here is an example:
import axios from 'axios'; const fetchData = async () => { const request = ('/some/url'); // Cancel the request at some point ('Operation canceled by the user.'); try { const res = await request; (); } catch (error) { if ((error)) { ('Request canceled:', ); } else { (error); } } };
In the above code, we first initiate a request and assign it to a variable request. Then, at the location where the request needs to be cancelled, we send the cancel request signal by calling the () method. If the request has been canceled, an error containing the reason for the cancellation is thrown and you can check for this error in the catch block and handle it.
This is the end of this article about the two methods of canceling requests for JavaScript. For more related contents for canceling requests for JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!