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
To handle 401 error in Axios and React, we can add a response interceptor. axios. interceptors. response.
axios. get('/user/12345') . catch(function (error) { if (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 ).
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); } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With