无法在vue端显示express res.send()自定义错误消息



我有一个带有express和mySQL的nuxt应用程序。

问题:我无法在vue端上显示express res.send((自定义错误消息

让我们假设我想显示一个用户的信息。

这是我的后端代码:

// Find a single User with a userId
exports.findOne = (req, res) => {
User.findById(req.params.userId, (err, data) => {
if (err) {
if (err.kind === 'not_found') {
res.status(404).send({
message: `Not found User with id ${req.params.userId}.`
})
} else {
res.status(500).send({
message: 'Error retrieving User with id ' + req.params.userId
})
}
} else { res.send(data) }
})
}

这是Vue部分

<script>
import axios from 'axios'
import appNavbar from '~/components/appNavbar.vue'
export default {
components: {
appNavbar
},
data () {
return {
userId: '',
userData: '',
errorMsg: ''
}
},
methods: {
fetchUser (evt) {
evt.preventDefault()
return axios.get('/api/users/' + this.userId)
.then((res) => {
this.userData = res.data
})
.catch((err) => {
this.errorMsg = err.toJSON()
})
}
}
}
</script>

当我给出一个不存在的用户的id时,我希望能够在后面写入自定义错误消息,并在前面的中显示它

但我只得到这个JSON

{ "message": "Request failed with status code 404", "name": "Error" }

有人知道线索吗?谢谢

此错误可能是因为您在第行调用API时未设置主机:

return axios.get('/api/users/' + this.userId)

404错误是因为浏览器找不到此端点。在这种情况下,我建议您尝试在另一个工具(如Postman(中调用此端点,并验证您的API是否正确响应。之后,修复对端点的调用,也许它会像下面的代码一样,然后重试:

return axios.get(`${your host here}/api/users/ + ${this.userId}`)

编辑:找到解决方案

答案如下:https://github.com/axios/axios/issues/960#issuecomment-309287911

在vue部分,catch应该返回err.response,而不仅仅是err。因此,为了显示您的自定义错误消息,它应该是这样的:

.catch((err) => {
this.errorMsg = err.response

最新更新