javascript - Axios:如何访问被拒绝 promise 的响应对象?

标签 javascript http axios

我使用 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 被拒绝,我留下了这个内置错误:请求失败,状态代码为 401。

有什么办法仍然可以访问响应对象吗?我的想法是处理来自服务器的所有错误消息,将这项工作从前端移开。

最佳答案

使用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
}

关于javascript - Axios:如何访问被拒绝 promise 的响应对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459624/

相关文章:

javascript - 获取 Base64 编码图像并使用 ExpressJS 将其作为图像发送

node.js - 如何使用 google-cloud/storage 的签名策略来上传数据?

javascript - 在 HOC 中使用 useState/Hooks 使用react导致错误 "Hooks can only be called inside of the body of a function component"

Javascript/CSS 加载并附加到文档

php - Symfony ajax 响应但带有 header : HTTP/1. 0 200 OK Cache-Control: no-cache Date

javascript - 在 React Native 中使用 axios 从带有参数的 GET 方法的 HTTP 响应

javascript - 加载网站时,如何在我的 React 应用程序上显示来自 Hacker News API 的所有故事?

javascript - 无论如何设置一个变量等于每次访问变量时调用的函数

javascript - 仅在内部元素上调用事件监听器(Javascript)

angularjs - 将 Angular $http.put 的数据元素的字符串转换为 JSON 对象