我对Nodejs / Mongo (和猫鼬)非常陌生。我使用bcrypt模块从HTML表单中散列密码。在我的db.create函数中,我无法将变量存储散列存储在mongodb中。
我没有发现任何错误,但它只是数据库中的空白。我已经检查了代码的每一行,它似乎正在工作。我不明白为什么不能将变量存储为“密码:存储散列”,而不允许存储诸如“密码:‘测试’”之类的内容
我肯定我在某个地方犯了什么错误。我很感谢你的帮助!
var db = require('../models/users.js');
var bcrypt = require('bcryptjs');
module.exports.createuser = function(req,res){
var pass = req.body.password;
var storehash;
//passsord hashing
bcrypt.genSalt(10, function(err,salt){
if (err){
return console.log('error in hashing the password');
}
bcrypt.hash(pass, salt, function(err,hash){
if (err){
return console.log('error in hashing #2');
} else {
console.log('hash of the password is ' + hash);
console.log(pass);
storehash = hash;
console.log(storehash);
}
});
});
db.create({
email: req.body.email,
username: req.body.username,
password: storehash,
}, function(err, User){
if (err){
console.log('error in creating user with authentication');
} else {
console.log('user created with authentication');
console.log(User);
}
}); //db.create
};// createuser function
发布于 2017-06-20 14:32:11
您的db.create应该在console.log(storehash);下面,而不是在bcrypt.salt之后。
当您将其放在bcrypt.salt之后时,您所做的是:当您为密码生成salt,然后哈希加密密码时,您还使用db.create将内容存储在数据库中。它们是同时执行的,而不是顺序执行的。这就是为什么,当您正在哈希密码时,您还创建了一个没有密码的db.create 的用户。
换言之,它应该是:
bcrypt.genSalt(10, function(err,salt){
if (err){
return console.log('error in hashing the password');
}
bcrypt.hash(pass, salt, function(err,hash){
if (err){
return console.log('error in hashing #2');
} else {
console.log('hash of the password is ' + hash);
console.log(pass);
storehash = hash;
console.log(storehash);
db.create({
email: req.body.email,
username: req.body.username,
password: storehash,
}, function(err, User){
if (err){
console.log('error in creating user with authentication');
} else {
console.log('user created with authentication');
console.log(User);
}
}); //db.create
}
});
}); https://stackoverflow.com/questions/44655510
复制相似问题