node.js - 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
解决方案
[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"
})
}
}
});
参考: 回调到底是什么?
推荐阅读
- flutter - 如何使用特定主机地址运行 firebase 模拟器?
- javascript - moment() 获取今天的午夜日期
- c# - 如何限制 UnityAds 并了解用户是否通过广告点击并安装了应用程序?
- python - Pytorch:计算子矩阵梯度的正确方法
- python - 在colab上导入bert微调模型
- visual-studio-code - VSC 打开错误的虚拟环境
- affinity - 在系统启动时自动设置 audiogd.exe 的亲和性
- javascript - 如何在 Php/Laravel 字符串变量中转义反引号?
- node.js - 等待不适用于 Sequelize 中的 QueryInterface.insert
- python - ffmpeg OSError: [WinError 6] 转换为exe时句柄无效