Node.js使用bcrypt验证用户名密码时程序崩溃问题求助
问题分析与修复方案
核心问题
- 空值访问导致进程崩溃:当查询不到用户(
!user)时,仅返回错误响应但未终止后续代码执行,后续尝试访问user.password时,user为undefined,直接抛出Cannot read properties of undefined (reading 'password')错误,导致Node.js进程终止。 - 重复响应触发错误:在
bcrypt.compare的回调中,密码不匹配时返回错误响应后未终止函数,后续仍会执行res.json("Login Success"),触发Cannot set headers after they are sent to the client错误。 - 缺失异常捕获:
await Admin.findOne()未包裹错误捕获逻辑,数据库查询出错时会直接抛出未捕获异常;bcrypt.compare也未处理可能的加密错误。
修复后的代码
router.post("/login", async (req, res) => { try { const { username, password } = req.body; const user = await Admin.findOne({ where: { username: username } }); if (!user) { return res.json({ error: "Admin User doesn't exist" }); } const match = await bcrypt.compare(password, user.password); if (!match) { return res.json({ error: "Username and password is incorrect" }); } res.json("Login Success"); } catch (err) { console.error("Login error:", err); res.status(500).json({ error: "Internal server error" }); } });
修复说明
- 用
return终止执行:返回错误响应时添加return,确保后续代码不再运行,避免空值访问和重复响应问题。 - 统一
async/await写法:将bcrypt.compare的链式调用改为await,简化代码逻辑,同时便于统一错误捕获。 - 全局异常捕获:用
try/catch包裹所有异步操作,捕获数据库查询、密码比对过程中的异常,返回通用服务端错误,避免进程意外终止。
内容的提问来源于stack exchange,提问作者Ramel Jay Cuña
相关产品推荐
相关产品推荐

