【问题标题】:Axios: How to access the response object, of a rejected promise?Axios:如何访问被拒绝的承诺的响应对象?
【发布时间】:2019-04-26 19:54:50
【问题描述】:

我已经使用 NodeJS 和 Express 构建了一些登录系统。我的错误处理基于发送适当的 http 状态代码,旁边自定义错误消息。例如,不正确的登录会返回:

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

如您所见,我既设置了一个会导致 promise 失败的状态(至少在 Axios 中),并且发送了我自己的错误。

在前端,这就是我所拥有的:

 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)
}

由于 401 导致 promise 被拒绝,我留下了这个内置错误:Request failed with status code 401。

还有什么方法可以访问响应对象吗?我的想法是处理来自服务器的所有错误消息,让这项工作远离前台。

【问题讨论】:

  • 控制台记录错误对象?
  • 错误对象不包含响应

标签: javascript http axios


【解决方案1】:

使用error.response 从服务器获取响应。要显示整个错误对象,请执行 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
}

【讨论】:

  • 好的,它可以工作,但不能用于 console.dir。只有console.log。不是我熟悉 console.dir :D 谢谢
猜你喜欢
  • 2020-09-10
  • 1970-01-01
  • 2017-01-20
  • 2020-11-21
  • 2018-05-09
  • 2017-03-28
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多