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