简体   繁体   中英

Axios: How to access the response object, of a rejected promise?

I've built some login system using NodeJS and Express. My error handling is based on sending the appropriate http status code, along side a custom error message. For instance, an incorrect login would return that:

res.status(401).send({ error: 'Incorrect login' })

As you can see, i'm both setting a status that will cause the promise to fail(at least with Axios), and sending my own error.

On the front end, this is what i have:

 try {
  var response =  await axios({
    method: 'post',
    url: 'http://localhost:3000/signin',
    data: {
      email: this.state.email,
      password: this.state.password
    },
    headers

  })
} catch (error) {
  console.log(response)
  return alert(error)
}

Being that 401 causes the promise to be rejected, i'm left with this built-in error: Request failed with status code 401.

Is there any way to still access the response object? My idea was to handle all error messages from the server, taking this job away from the front.

Use error.response to get the response from server. For revealing the whole error object, do a console.dir(error)

try {
  var { data } = await axios({
    method: 'post',
    url: 'http://localhost:3000/signin',
    data: {
      email: this.state.email,
      password: this.state.password
    },
    headers

  })
} catch (error) {
  console.dir(error) // error.response contains your response
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM