在节点 .js 中尝试错误的登录凭据后,应用崩溃



这是我的登录代码,当用户输入正确的凭据时它的工作,但是当应用程序输入错误的凭据时,应用程序崩溃了,显示错误消息"内部服务器错误"是正确的,因为我在它捕获代码中写了东西,但我想要的是,当用户输入错误的凭据时,应用程序不应该崩溃。

router.post(
"/login",
[
body("email", "you enter wrong email").isEmail(),
body("password", "password cannot be blank").exists(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
res.status(400).json({ error: "Please try to login with correct credentials" });
}
const passwordcompare = await bcrypt.compare(password, user.password);
if (!passwordcompare) {
res.status(400).json({ error: "Please Try to login with correct credential" });
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWTSECRET);
res.json({ authtoken });
} catch (error) {
console.log(error.message);
res.status(500).send("Internal  server error");
}
},
);
module.exports = router;

你不会return那些res.status(400).json(),所以你的程序只是继续它的快乐方式。

if (!user) {
res.status(400).json({error: "Please try to login with correct credentials"});
return;  // add this
}

我认为这一行的问题

const passwordcompare = await bcrypt.compare(password, user.password);

当密码未定义或错误时,bcrypt.compare 将抛出错误,catch 块将捕获它并返回内部服务器错误消息

尝试将返回添加到 res

if (!passwordcompare) {
return res.status(400).json({ error: "Please Try to login with correct credential" });
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWTSECRET);
return res.json({ authtoken

});

你不返回res.status(),这就是你的代码崩溃的原因。

最新更新