0
votes

I am making a request from the front-end to a route in my backend that is validating the token associated with a user, which would send an error response back to the front-end if the token has expired. I am sending some json with it but upon doing console.log of the error message in the catch block, the json sent along the error response is not shown.

Sending the error response like this

res.status(401).json({
                message: 'User session has expired'
            })

But the response that I am getting in the catch block in the front-end has no sign of the json sent with the error.

POST http://localhost:3001/check-validation 401 (Unauthorized) Error: Request failed with status code 401 at createError (createError.js:17) at settle (settle.js:19) at XMLHttpRequest.handleLoad (xhr.js:78)

I don't understand why the json sent along the error response is not shown and how to get it?

1

1 Answers

0
votes

Upon doing console.log of the error only the stacktrace of the error is shown and not the data associated with it. The data sent with it can be procured and depends on how the request has been made or by what library it has been made. If the request is made by axios then the following can be done:

axios.post('/formulas/create', {
    name: "",
    parts: ""
})
.then(response => { 
    console.log(response)
})
.catch(error => {
    console.log(error.response.data.message)
});

Here, in axios the details of the error would be wrapped up in error.response. Whereas, if the request was made by the fetch API then something following can resolve the problem:

fetch('/401').then(function(response) {
  if (response.status === 401) {
    return response.json()
  }
}).then(function(object) {
  console.log(object.message)
})

P.S I was searching a lot regarding this problem but didn't get an answer on SO, neither got any article or docs regarding it, even the official Express docs on error handling were not helpful. At last, I understood that the problem lies with the library that is being used to make the request. That's why answering my own question to mark the presence of this question on SO. A detailed discussion can be found here related to axios and here related to fetch api