我有下面提到的node.js代码:
router.post("/addData", async (req, res)=>{
const password = req.body.password;
console.log("before.password: ", password);
await bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
if (err) {
console.log("bcrypt error: ", err);
}
console.log("hash passw: ", hash);
password = hash;
});
});
console.log("after.password: ", password);
});
实际输出是:
before.password: passw
after.password: passw
hash passw: $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG
我需要输出,预期输出如下所示:
before.password: passw
hash passw: $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG
after.password: $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG
当打印密码出bcrypt块时,我们得到普通密码没有哈希,我知道bcrypt正在工作,密码已成功散列,但我们无法从bcrypt块中获取哈希密码。
请帮助我解决同样的问题,我想我在某些时候错误地放置了代码。提前致谢。
您正在使用两种方法来处理异步代码。当你这样做
bcrypt.genSalt(10, (err, salt) => {
// callback code here
})
你正在使用回调。回调是genSalt函数完成时执行的函数。所以你告诉程序:“当genSalt完成运行此代码时”
处理异步代码的另一种方法是使用带有async / await的promises。所以基本上你说:“等待这个并给我回报价值”
const hash = await bcrypt.genSalt(10) // waiting for promise, no callback.
在您的代码中,您正在执行这两个版本。
另请注意,bcrypt也有genSaltSync
和hashSync
方法。所以你可以这样做:
router.post("/addData", (req, res)=>{
const password = req.body.password;
console.log("before.password: ", password);
const salt = bcrypt.genSaltSync(10);
const hash = brypt.hashSync(password,salt)
console.log("after.password: ", hash);
});
请注意,在此示例中,处理程序没有async关键字。因为我们使用的是同步方法。