当我输入错误的凭据登录时,我的节点模型会崩溃



我正试图在node.js中进行登录路由,但当我输入错误的凭据时,我的应用程序会崩溃

这是我的登录路线,请告诉我做错了什么

router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
!user && res.status(400).json("User Not exist!");
const validated = await bcrypt.compare(req.body.password, user.password);
!validated && res.status(400).json("Invalid Password!");
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json(err);
}
});

你能在响应之前添加一个返回并使你的代码更干净吗?问题是,当你写res.status(400(时…代码将继续到下一步,应用程序将崩溃,所以你的代码应该像一样

router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return res.status(400).json("User Not exist!");
}
const validated = await bcrypt.compare(req.body.password, user.password);
if (!validated) {
return res.status(400).json("Invalid Password!");
}
const { password, ...others } = user._doc;
return res.status(200).json(others);
} catch (err) {
return res.status(500).json(err);
}
});

最新更新