You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用bcrypt验证用户名密码时程序崩溃问题求助

问题分析与修复方案

核心问题

  1. 空值访问导致进程崩溃:当查询不到用户(!user)时,仅返回错误响应但未终止后续代码执行,后续尝试访问user.password时,user为undefined,直接抛出Cannot read properties of undefined (reading 'password')错误,导致Node.js进程终止。
  2. 重复响应触发错误:在bcrypt.compare的回调中,密码不匹配时返回错误响应后未终止函数,后续仍会执行res.json("Login Success"),触发Cannot set headers after they are sent to the client错误。
  3. 缺失异常捕获: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:40:31