Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a 401 with axios and stop the console error

Tags:

I am trying to use axios to call an API and return data.

I have the following code which works fine

axios.get('http://api/courses')   .catch(function (error) {     if (error.response) {       console.log(error.response.status);     } else {       console.log('Error', error.message);     }   })   .then(response => {     console.log(response.data)   }); 

This works fine, the API returns a 200 and data so in the console I get the data returned.

However this does not work

axios.get('http://api/courses')   .catch(function (error) {     if (error.response) {       console.log(error.response.status);     } else {       console.log('Error', error.message);     }   })   .then(response => {     console.log(response.data)   }); 

On the above call i get a 401 returned from the API, I want to be able to detect that and do something (where i am currently doing a console.log). However in the console I get the following errors:

GET http://api/courses 401 (Unauthorized) (anonymous) @ spread.js:25 e.exports @ spread.js:25 e.exports @ spread.js:25 Promise.then (async) r.request @ spread.js:25 r.(anonymous function) @ spread.js:25 (anonymous) @ index.js:20 (anonymous) @ (index):49   (index):58 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at axios.get.catch.then.response ((index):58) at <anonymous> 

Is there a way to capture a 401? It seems like common practice by API's that require auth, but I cannot seem to work it out. Thanks

like image 511
davidjh Avatar asked Feb 12 '18 09:02

davidjh


People also ask

How do you handle 401 authentication error in Axios and react?

To handle 401 error in Axios and React, we can add a response interceptor. axios. interceptors. response.

How do you handle errors in Axios?

axios. get('/user/12345') . catch(function (error) { if (error.

Does Axios post throw error?

By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ).


1 Answers

You can add an interceptor that will catch all 401 responses. That way you can fire a redirect or any sort of actions you might need. In this example I am dispatching a redux action that will clean up some user data and render the login form.

const UNAUTHORIZED = 401; axios.interceptors.response.use(   response => response,   error => {     const {status} = error.response;     if (status === UNAUTHORIZED) {       dispatch(userSignOut());     }     return Promise.reject(error);  } ); 
like image 191
Bruno Paulino Avatar answered Sep 27 '22 19:09

Bruno Paulino