我在访问返回400错误的JSON对象时遇到了一些困难。
我的Vue应用程序的响应仅是错误400,没有JSON数据。
Error: Request failed with status code 400
at createError (createError.js?16d0:16)
at settle (settle.js?db52:18)
at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)
使用Postman从同一用户返回的响应将返回错误代码和消息。
如何在Vue应用程序中访问JSON响应?
{
"error": "Email already exists!"
}
Express API代码:
res.status(400).json({ error: 'Email already exists!' });
我的Vue代码:
handleSubmit () {
this.$http.post('http://localhost:3000/users/create', this.user)
.then(response => {
const status = JSON.parse(response.status)
if (status === 200) router.push('/users')
})
// why doesn't the json response show
.catch(err => {
console.log(err)
})
}
答案 0 :(得分:0)
尝试发送而不是json吗?也可能访问错误。
BACKEND
res.status(400).send({ error: 'Email already exists!' })
FRONTEND
(err) => { console.log(err["error"]) }
答案 1 :(得分:0)
您必须使用response
属性或error
对象:
handleSubmit () {
this.$http.post('http://localhost:3000/users/create', this.user)
.then(response => {
// if on server side you use only status 200, here it's always true
if (response.status=== 200) {
router.push('/users');
}
})
.catch(error => {
// error.response can be null
if (error.response && error.response.status === 400) {
console.log(error.response.data.error);
}
})
}
See关于axios错误处理的文档