close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to handle 401 (Authentication Error) in axios and react? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

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

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

    to handle 401 (Authentication Error) in axios and react axios.interceptors.response.use(response => {
    return response;
    }, error => {
    if (error.response.status === 401) {
    //place your reentry code
    }
    return error;
    });

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

    to handle 401 (Authentication Error) in axios and react axios.interceptors.response.use(response => {
    return response;
    }, error => {
    if (error.response.status === 401) {
    //place your reentry code
    }
    return error;
    });

Method 1

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;
});

Method 2

We can catch axios 401 using this method.

 axios.post('/add')
 .then(function (response) {...})
 .catch(function (error) {
     console.log(error.response.status) // 401
     console.log(error.response.data.error) //Please Authenticate or whatever returned from server
   if(error.response.status==401){
     //redirect to login
   }
 })

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment