【发布时间】:2019-03-04 02:34:02
【问题描述】:
我不明白fetch 如何将错误消息从后端返回到前端。我不确定要在前端的fetch 函数的错误代码中添加什么样的属性。目标是发送错误(“电子邮件地址是..”)并将其显示在 UI 中。
后端发布请求详细信息。如果用户已经注册,则抛出 400 错误。
const signupPost = function (req, res) {
Base.findOne({
userName: req.body.userName
},
function (user, err) {
if (err) {
return res.status(400).send({
error: 'The email address you have entered is already associated with another account.'
});
}
这是我的 Vue 前端的错误处理方法:
methods: {
signup() {
this.errorMessage = '';
if (this.validUser()) {
const body = {
userName: this.user.userName,
firstName: this.user.firstName,
lastName: this.user.lastName,
telephone: this.user.telephone,
password: this.user.password
}
fetch(SIGNUP_URL, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'content-type': 'application/json'
}
})
.then((response) => {
if (response.ok) {
return response.json();
}
return response.json().then((error) => {
throw new Error(error);
})
})
.then(user => {
console.log(user)
})
.catch((error) => {
this.errorMessage = error
});
}
},
【问题讨论】:
标签: node.js express vue.js fetch