1 year ago
#370012

Bob
React: Getting undefined when handling error response in Axios
I'm trying to handle error responses from a api call, but when i get error status in browser like 404 or 403. It seems like i can't console.log error.responses. I'm using PHP for back-end, but i'm unsure if it's a problem from back-end or front-end.
Front-End code:
async function getData() {
await axios({
method: 'POST',
url: `${process.env.REACT_APP_API_BASEURL}/test/`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
"Authorization": `Bearer #####`
},
data: {
test: test
}
})
.then((res) => {
console.log(res.data)
})
.catch((error: any) => {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
console.log(error.response.status);
console.log(error.headers);
console.log(error.response);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the
// browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
//console.log(error.config);
})
}
Back-end code snip (What i'm sending in response):
$error = 403;
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
http_response_code($error);
print json_encode(array('status'=> $error), JSON_FORCE_OBJECT);
However, if i try to console.log(error.response) i get undefined. Any reason why?
php
reactjs
error-handling
axios
undefined
0 Answers
Your Answer