密码不希望在生成

时间:2016-08-31 06:00:56

标签: json node.js mongoose bcrypt

我尝试保存哈希密码时遇到问题。当我以前用它保存它的工作方式时,但现在我实现了bcrypt它不再工作了。返回的JSON甚至不包含密码。

这是我的代码:

用户模型:

 49 userSchema.methods.registerUser = function(page, body, cb) {
 50   if (page == 1) {
 51     this.username = body.username;
 52     this.email = body.email;
 53     this.generatePassword(body.password, function(err, hash) {
 54       if (err) cb(err);
 55       this.password = hash;
 56     });
 57   } else if (page == 2) {
 58     this.firstName = body.firstName;
 59     this.lastName = body.lastName;
 60     this.gender = body.gender;
 61     this.dateOfBirth = this.createDate(body.day, body.month, body.year);
 62     this.age = this.calculateAge(this.dateOfBirth);
 63   } else {
 64     cb("ERR! Page " + page + " doesnt exist");
 65   }
 66
 67   cb();
 68 };

 84 userSchema.methods.generatePassword = function(password, cb) {
 85   bcrypt.hash(password, null, null, function(err, hash) {
 86     cb(err, hash);
 87   })
 88 };

用户控制器:

 11 router.post('/register/:page', function(req, res) {
 12   user.registerUser(req.params.page, req.body, function() {
 13     if (req.params.page == 1) res.redirect('/register/2');
 14     if (req.params.page == 2) res.json(user);
 15   });
 16 });

返回JSON:

{"email":"ivan@gmail.com","username":"ivanerlic","age":21,"dateOfBirth":"1994-09-01T05:58:43.204Z","gender":"male","lastName":"Erlic","firstName":"Ivan","_id":"57c670438b0d398f07371386"}

正如您所看到的,它不会返回密码。我做错了什么?

2 个答案:

答案 0 :(得分:1)

这是因为有this冲突。

userSchema.methods.registerUser = function(page, body, cb) {
 50   if (page == 1) {
 51     this.username = body.username;
 52     this.email = body.email;
        var self = this;
 53     this.generatePassword(body.password, function(err, hash) {
 54       if (err) return cb(err);
 55       self.password = hash;
 56     });
 57   } else if (page == 2) {
 58     this.firstName = body.firstName;
 59     this.lastName = body.lastName;
 60     this.gender = body.gender;
 61     this.dateOfBirth = this.createDate(body.day, body.month, body.year);
 62     this.age = this.calculateAge(this.dateOfBirth);
 63   } else {
 64     cb("ERR! Page " + page + " doesnt exist");
 65   }
 66
 67   cb();
 68 };

答案 1 :(得分:0)

您在执行哈希之前调用回调。 正确的代码应该是:



49 userSchema.methods.registerUser = function(page, body, cb) {
 50   if (page == 1) {
 51     this.username = body.username;
 52     this.email = body.email;
 53     this.generatePassword(body.password, function(err, hash) {
 54       if (err) cb(err);
 55       this.password = hash;
         cb();
 56     });
 57   } else if (page == 2) {
 58     this.firstName = body.firstName;
 59     this.lastName = body.lastName;
 60     this.gender = body.gender;
 61     this.dateOfBirth = this.createDate(body.day, body.month, body.year);
 62     this.age = this.calculateAge(this.dateOfBirth);
         cb();
 63   } else {
 64     cb("ERR! Page " + page + " doesnt exist");
 65   }
 68 };




如果仍然无效,请使用self,如同在另一个答案中一样。