這是我的登錄代碼,當用戶輸入正確的憑據時,應用程式在輸入錯誤的憑據時崩潰,顯示錯誤訊息“內部服務器錯誤”,這是正確的,因為我在其中寫了捕獲代碼,但我想要什么當用戶輸入錯誤的憑據時,應用程式不應崩潰。
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;
uj5u.com熱心網友回復:
你不是return在追求那些res.status(400).json()s,所以你的程式只是繼續它快樂的方式。
if (!user) {
res.status(400).json({error: "Please try to login with correct credentials"});
return; // add this
}
uj5u.com熱心網友回復:
我認為這一行的問題
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
});
uj5u.com熱心網友回復:
您應該在錯誤檢查中添加陳述句,否則, 如果未找到用戶return,該函式將繼續執行并嘗試訪問:user.password
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) {
return res.status(400).json({ error: "Please try to login with correct credentials" });
}
const passwordcompare = await bcrypt.compare(password, user.password);
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);
res.json({ authtoken });
} catch (error) {
console.log(error.message);
res.status(500).send("Internal server error");
}
},
);
module.exports = router;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505606.html
標籤:javascript 节点.js 反应
上一篇:如何避免通過setInterval的新執行覆寫變數值
下一篇:在兩個字符之間拆分字串?
