Reputation: 519
I'm using node+express in my backend, and react on front. In node, I send the client a 400 error response:
return res.status(400).send("Invalid username!")
And in react, I call this api through axios with this:
await axios.post(url, user)
.then(res => {
if (res.status === 200) {
console.log("logged!")
}
else {
console.log(res)
}
})
When I purposely enter the wrong credentials for the object user
, it would give me the 400 (Bad Request)
error. However, I cannot get the invalid username
message. I look on the Network panel (Chrome) and there I could see the message. How do I get that message response?
I tried:
res.message
res.error
res.errors
res.body
Nothing worked. Thanks a lot!
But
Upvotes: 0
Views: 2976
Reputation: 180
I came across same problem. err.message
was shown as a generic message, based on status code, even if I used json
response:
response.status(400).json({
message: "Invalid username!",
});
Best way to fix this is to console.log()
your err
and find where your custom message is hiding.
Axios
library seems to put it a little deeper as I would expect. Mine was hiding in err.response.data.message
If you are using Typescript, this a code to keep it happy:
import axios, { AxiosError } from "axios";
......
try {
.....
}
catch (err) {
if (err instanceof AxiosError && !!err.response) {
setError(err.response.data.message);
} else {
setError("<Some other error message>");
}
}
Upvotes: 0
Reputation: 9063
Firstly, you're mixing async/await
syntax with .then/.catch
. It doesn't work like that, you need to do one or the other.
Secondly, that's not the right way to catch errors when using the .then/.catch
syntax, you need the .catch
method to catch those errors. If you want to use async/await
, then you need to use a try/catch block.
So it needs to be like this:
axios.post(url, user)
.then(res => {
console.log("logged!")
})
.catch(err => {
console.log(err);
})
Or like this:
try {
const response = await axios.post(url, user);
console.log(response);
}
catch (err) {
console.log(err);
}
Upvotes: 3