I am trying to log out a user when the response code is 401. I managed to do it with axios interceptors, and while it works, it also runs the catch block in the main axios call, which is something I don't want.
Eg: the user tries to create a post, they're not authorized so it either shows "Unauthorized" or "Not valid", if the error is undefined, which is what's happening with the interceptors right now. Is there any way to fix it?
axios.interceptors.response.use(
(response) => response,
(err) => {
if (err.response.status === 401) {
logout()
} else {
return Promise.reject(err);
}
}
);
You can set the validateStatus to true to stop axios from throwing an error. Then you can check your response status code to see if the request was successful or failed.
You can change validateStatus this way:
axios.defaults.validateStatus = function() {
return true;
};
In case you only want to pass errors with code 2xx and 4xx you can use the code below:
axios.defaults.validateStatus = function(status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 500);
};
It is also possible to only pass errors with code 2xx and 401 using the code below:
axios.defaults.validateStatus = function(status) {
return (status >= 200 && status < 300) || status === 401;
};
in case you don't want to use this on a global scale you can just use it in the config of the one of the requests that you want to send like below:
axios.post('/auth', {}, {
validateStatus: function (status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 500);
}
});