I’m trying to call a post request from Next.js app. However, there is a cancel button to stop the post request. I’m trying abortController
with Axios (v1.4.0) to stop the post request.
When I’m calling the cancel function ‘cancelUploadHandler’ it’s being called, but request isn’t stopping.
const abortController = new AbortController()
const completeHandler = async () => {
try {
const response = await axios.post(
process.env.APP_URL + "post-url/",
data,
{
onUploadProgress: (progress) => {
console.log(progress)
},
withCredentials: true,
signal: abortController.signal
}
);
return response.data;
} catch (error) {
if (axios.isCancel(error)) {
console.log("Request canceled:", error.message);
} else {
console.log(error)
}
}
};
const cancelUploadHandler = () => {
console.log("CANCEL REQUEST")
abortController.abort()
}
2
Answers
You can’t “undo” a network request that already happened. All the
abort()
does is to stop the asynchronous task related to the network in your JavaScript environment. As you can read on MDN:If click the cancel button before the request has completed, you would enter the
catch
blog with an error. But for the server that’s called, nothing changes.We create an instance of AbortController and get the signal property from it.
When making the fetch request, we pass the signal to the signal option of the fetch request.
Later, if you want to abort the request, you can call the abort() method on the controller. This will cause the fetch request to throw an AbortError and reject the promise returned by fetch().