Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching error messages from a NodeJS express application using axios

I have an application using NodeJS in backend and specifically Express framework to serve API routes. My client side is written in ReactJS, making use of axios to make API requests.

First time using axios package, and i can't find how to access error messages from the response.

My API returns as error responses:

res.status(404).send({ error: 'Error Message' });

In axios i have:

axios.post('/api/users', newUser)
  .then((user) => {
    console.log(`User created: ${JSON.stringify(user)}`);
  }).catch((err) => {
    console.log(`Error : ${JSON.stringify(err)}`);
  });

console.log(`Error : ${JSON.stringify(err)}`) prints:

{
  "message": "Request failed with status code 404",
  "name": "Error",
  "stack": "Error: Request failed with status code 404\n    at createError (http://localhost:3000/static/js/0.chunk.js:13853:15)\n    at settle (http://localhost:3000/static/js/0.chunk.js:14074:12)\n    at XMLHttpRequest.handleLoad (http://localhost:3000/static/js/0.chunk.js:13328:7)",
  "config": {
    "url": "/api/users",
    "method": "post",
    "data": "someData",
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Authorization": "Bearer xxxxx",
      "Content-Type": "application/json;charset=utf-8"
    },
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1
  }
}

I can't find nowhere in that err object the response message from the server, i have even tried:

res.status(404).json({ error: 'Error Message' });

with no success.

like image 619
Konstantinos Lamogiannis Avatar asked Dec 09 '25 21:12

Konstantinos Lamogiannis


1 Answers

Per this comment, try accessing err.response in the catch block.

like image 74
Aaron Avatar answered Dec 12 '25 13:12

Aaron



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!