How to handle 401 (Authentication Error) in axios and react?

Amir Saleem picture Amir Saleem · Nov 10, 2017 · Viewed 72.5k times · Source

I have one file request.js which contains wrapper for axios ajax request. I am calling request function from multiple react components and when one of the request fails I want to refresh the token and retry all the failed requests again. I can use intercepters, but I don't know how to implement it. Please help.

request.js

 var client = axios.create({
   baseURL: 'http://192.168.1.3:3000',
     headers: {
     appID: 8,
     version: "1.1.0",
     empID: localStorage.getItem('empID'),
     token: localStorage.getItem('accessToken')
    }
 });

 const request = function(options) {
     const onSuccess = function(response) {
         console.debug('Request Successful!', response);
         return response.data;
     } 
     const onError = function(error) {
         console.error('Request Failed:', error.config);
         if (error.response) {
             console.error('Status:',  error.response.status);
             console.error('Data:',    error.response.data);
             console.error('Headers:', error.response.headers);
         } else {
             console.error('Error Message:', error.message);
         }

         return Promise.reject(error.response || error.message);
     }

     return client(options)
         .then(onSuccess)
         .catch(onError);
         options
 }

 export default request;

Answer

Pram picture Pram · Nov 10, 2017

If you want to use interceptors to handle 401 error here is code snippet.

axios.interceptors.response.use(response => {
   return response;
}, error => {
  if (error.response.status === 401) {
   //place your reentry code
  }
  return error;
});