Reputation: 159
I'm having some difficulty accessing the JSON object returned with a 400 error.
The response from my Vue app is only error 400, without the JSON data.
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)
The response from the same using Postman returns both the error code and the message.
How do I access the JSON response in my Vue app?
{
"error": "Email already exists!"
}
Express API code:
res.status(400).json({ error: 'Email already exists!' });
My Vue code:
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)
})
}
Upvotes: 0
Views: 3705
Reputation: 1423
You must use response
property or error
object:
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 documentation of axios error handling
Upvotes: 9
Reputation: 2807
Try send instead of json? Also perhaps accessing error.
BACKEND
res.status(400).send({ error: 'Email already exists!' })
FRONTEND
(err) => { console.log(err["error"]) }
Upvotes: 0