【发布时间】:2019-10-24 03:58:10
【问题描述】:
我正在使用 react 和 express。在反应应用程序中,我想使用 axios.post 将用户的凭据发送到快递服务器,并希望收到它的响应。从响应中我想提取消息和状态。它看起来像这样:
handleSubmit = e => {
e.preventDefault();
const { email, password } = this.state;
axios
.post("/api/users/login", {
email,
password
})
.then(res => console.log(res.data.msg, res.status))
.catch(err => console.log(err));
};
在后端,我使用猫鼬模型来确定用户是否已存在于数据库中。
router.post("/login", (req, res) => {
const { email, password } = req.body;
User.findOne({ email })
.then(user => {
if (!user) return res.status(400).json({ msg: "No such user in the DB" });
bcrypt.compare(password, user.password).then(isMatch => {
if (!isMatch) {
return res.status(400).json({ msg: "Wrong password" });
}
req.session.userId = user.id;
res.status(200).json({ msg: "You have logged in" });
});
})
.catch(err => console.log("Error in catch in findOne"));
});
如果一切顺利,并且数据库中存在具有这些凭据的用户,我会按预期在控制台中收到消息“您已登录”和状态 200 但 如果发生错误,我不会收到 axios 响应自定义错误消息,例如“数据库中没有此类用户”或“密码错误”,而是收到默认错误,我猜,它看起来像这样:
xhr.js:166 POST http://localhost:3000/api/users/login 400 (Bad Request)
Login.js:21 Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
我的问题是:如果出现任何问题,我如何才能获得自己的错误消息而不是默认消息。例如:如果密码不正确,我希望在 axios 响应“数据库中没有此类用户”中收到此消息。
【问题讨论】:
-
你发回的
msg字段不还是自定义的吗? -
是自定义的,但是如果密码错误或用户不在数据库中,我在axios响应中没有收到。我刚刚在控制台中收到这条消息:xhr.js:166 POST localhost:3000/api/users/login 400 (Bad Request)