加密密码比较未显示结果



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

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"

但它跳过了bcrypt.compare()内部if语句,并以message: "wohhoo"

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

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

// 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"
            })
        }
    }
});

参考:回调到底是什么?

最新更新