I have the following code snippet which does an api request to my backend to get back an user object in json or a status code of 401 if the user is not authenticated, along with the status code it should receive a message.
<script>
axios
.get("http://localhost:5000/get-authenticated-user")
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
My API route looks like this:
router.get("/get-authenticated-user", (req, res) => {
if (req.user) {
res.json({ user: req.user });
}
res.status(401).json({ err: "Not authenticated" });
});
However when a user is not authenticated it only gives me back the following error message (in the catch block) and not the "Not authenticated" message which is supplied from my API.
Error: Request failed with status code 401
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.E (xhr.js:66)
The authentication is working and all, it's just the error message not showing properly when the user is not authenticated. I've been struggling with this for a while, anyone has an idea?
You can retrieve the 401 response body data by inspecting error.response.data in the error callback:
<script>
axios
.get("http://localhost:5000/get-authenticated-user")
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
console.log(error.response.data);
});
</script>
In your case it will displays the object having the err field you returned from the Express server.
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