Cancelling a api request made to server
Wed Dec 29 2021 14:52:51 GMT+0000 (Coordinated Universal Time)
Saved by
@Shubham
//1st with browser's default AbortController
const controller = new AbortController();
const signal = controller.signal;
try{
axios.get('http://example.com',{
signal,
})
}catch(error=>{
if (err.name === "AbortError") {
console.log('cancelled by browser or user');
}
//handle other errors
})
controller.abort(); // aborts the above request with an `AbortError`
//2nd with axios
// before sending the request
const source = axios.CancelToken.source();
// then pass-in the token with request config object
try{
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
});
}catch(error=>{
if(axios.isCancel(error)){
console.log('cancelled by axios');
}else{
//handle other errors
}
})
// upon cancelation
source.cancel('Operation canceled by the user');
content_copyCOPY
https://github.com/axios/axios/issues/3506
Comments