首页 > 解决方案 > Bcrypt密码比较不显示结果

问题描述

我遇到了一个奇怪的问题。我在里面有一个 if 语句bcrypt.compare(),它根本不运行。

例子

bcrypt.compare(req.body.password, data.password, function (err, result) {

    if (!result || err) {
        res.status(422).json({
            message: "Wrong Password",
            status: false,
            statusCode: 422
        })
    }

});

const otherData = await findOne({
    x : req.body.x
})

if(otherdata.x == "dummy") {

    return res.status(200).json({
        message: "wohhooo"
    })
}

当我发送错误的密码时,request body它应该回复message: "wrong password"

但它会跳过if里面的那个语句bcrypt.compare()并用message: "wohhoo"

在控制台中我看到,Error: Can't set headers after they are sent.错误指向return里面的语句bcrypt.compare

标签: node.jsmongodbexpressmongoosebcrypt

解决方案


[bcrypt.compare] 1是异步函数,所以你的程序在执行 res.status(200).json({message: "wohhooo"})之前bcrypt.compare

// Quick Fix
bcrypt.compare(req.body.password, data.password, function (err, result) {
    if (!result || err) {
        return res.status(422).json({
            message: "Wrong Password",
            status: false,
            statusCode: 422
        })
    } else {
        const otherData = await findOne({
            x: req.body.x
        })
        if (otherdata.x == "dummy") {
            return res.status(200).json({
                message: "wohhooo"
            })
        }
    }
});

参考: 回调到底是什么?


推荐阅读