Sometimes, we want to handle 401 error in Axios and React.
In this article, we’ll look at how to handle 401 error in Axios and React.
How to handle 401 error in Axios and React?
To handle 401 error in Axios and React, we can add a response interceptor.
For instance, we write
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response.status === 401) {
// ...
}
return error;
}
);
to call axios.interceptors.response.use
with a function that runs when we get a response and a function that runs when we get an error respectively.
In the error handling function, we get the response status code with error.response.status
.
If it’s 401, then we do some thing with the response.
Conclusion
To handle 401 error in Axios and React, we can add a response interceptor.