我正在使用 yortus' async/await node.js 库,用于设置基于 Passport 的登录/注册系统,其密码使用 bcrypt-nodejs 进行哈希处理。 .
虽然系统的其余部分已设置并正常运行,但我在使 bcrypt-nodejs
与 yortus 的 async/await
良好配合时遇到了麻烦,因为 bcrypt哈希函数签名需要两个回调,目前尚不清楚如何将其与async/await
一起使用...
hash(data, salt, progress, cb)
data - [REQUIRED] - the data to be encrypted.
salt - [REQUIRED] - the salt to be used to hash the password.
progress - a callback to be called during the hash calculation to signify progress
callback - [REQUIRED] - a callback to be fired once the data has been encrypted.
error - First parameter to the callback detailing any errors.
result - Second parameter to the callback providing the encrypted form.
async/await
调用...
let generateHash = async((password) => {
let salt = await(bcrypt.genSaltAsync(10)) // this works
let result = await(bcrypt.hash(password, salt, null)
return result // returns NULL
})
输出:
Unhandled rejection No callback function was given.
当我尝试使用系统注册时的数据库条目(MongoDB):
{
"_id" : ObjectId("581bf7031386f167a09851b9"),
"username" : "vjk2005",
"password" : ""
}
用户名通过,但密码为NULL
。我尝试了多种排列和组合,但没有成功,感谢您的帮助。
最佳答案
我建议在 Node 7 上仅将 babel
与常规 async/await
关键字或 --harmony-async-await
标志一起使用。使代码更简洁,我认为很少有人使用该库。他们采纳了这个想法并将其变成了语言的一部分。
即使您使用该库,它也需要 promise 的函数而不是使用回调的函数。您可以使用 pify
模块或查找 promisified bcrypt。始终在 npmjs.com 或 npms.io 上搜索。搜索“bcrypt Promise”。
import {hash} from 'bcrypt-as-promised';
const generateHash = async password => await hash(password, 10);
generateHash('abc1234').then(console.log).catch(console.error);
或者因为您可以像这样自动生成盐,所以您可以将其简化为:
import {hash} from 'bcrypt-as-promised';
hash('abc123',10).then(console.log).catch(console.error);
关于javascript - 设置 bcrypt 以与 Passport 和 async-await Node.js 库配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414629/