【问题标题】:Nodejs, bcrypt , MongooseNodejs,bcrypt,猫鼬
【发布时间】:2017-06-20 22:37:25
【问题描述】:

我对 Nodejs / Mongo(使用 Mongoose)非常陌生。我正在使用 bcrypt 模块从 HTML 表单中散列密码。在我的 db.create 函数中,我无法将变量 storehash 存储在 mongodb 中。

我没有收到任何错误,但它在数据库中只是空白。我已经检查了代码的每一行,它似乎正在工作。我不明白为什么我不能将变量存储为“密码:storehash”,而我可以存储诸如“密码:'test'”之类的东西

我确定我在某个地方犯了一些菜鸟错误。如有任何帮助,我将不胜感激!

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

【问题讨论】:

  • 代码示例!
  • 使用提供的代码格式化程序,所以不要发布代码的图像
  • 哈哈,我想我就是这么做的。谢谢!
  • 欢迎来到 SO ...始终通过点击答案旁边的复选标记小部件来确认您的问题的正确答案...这会给您积分,但更重要的是它告诉其他人答案是有效的 - 小心
  • 听起来不错!谢谢!

标签: node.js mongodb mongoose bcrypt


【解决方案1】:

您的db.create 应该在console.log(storehash); 的正下方,而不是在bcrypt.salt 之后。

当您将它放在bcrypt.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
        }
    });

}); 

【讨论】:

  • 哦,是的!正确的。知道了。我相信我将同步编程与节点异步性质混为一谈。它现在正在工作。非常感谢!!
猜你喜欢
  • 2018-06-09
  • 2017-06-26
  • 1970-01-01
  • 2017-06-30
  • 2020-09-18
  • 2021-06-01
  • 2016-02-05
  • 2021-03-17
  • 1970-01-01
相关资源
最近更新 更多