Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios does not return proper error message

Tags:

node.js

axios

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?

like image 639
sharpness Avatar asked Mar 13 '26 13:03

sharpness


1 Answers

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.

like image 129
Delapouite Avatar answered Mar 16 '26 01:03

Delapouite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!