我使用 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/