bcrypt-node正在抛出错误"没有给出回调函数"

时间:2016-09-17 04:52:17

标签: node.js passport.js jwt

我正在使用JWT身份验证创建用户注册。我正在使用bcrypt-node模块进行密码哈希和盐渍。

useraModel.js

var mongoose    =require('mongoose');
var Schema      =mongoose.Schema;
var bcrypt      =require('bcrypt-node');

var UserSchema=new Schema({
    name:{type:String, unique:true, required:true},
    password:{type:String, required:true}
});

    UserSchema.pre('save', function (next) {
        var user = this;
        if (this.isModified('password') || this.isNew) {
            bcrypt.genSalt(10, function (err, salt) {
                if (err) {
                    return next(err);
                }
                bcrypt.hash(user.password, salt, function (err, hash) {
                    if (err) {
                        return next(err);
                    }
                    user.password = hash;
                    next();
                });
            });
        } else {
            return next();
        }
    });

    UserSchema.methods.comparePassword = function (passw, cb) {
        bcrypt.compare(passw, this.password, function (err, isMatch) {
            if (err) {
                return cb(err);
            }
            cb(null, isMatch);
        });
    };

    module.exports = mongoose.model('User', UserSchema);

passport.js

var JwtStrategy     =require('passport-jwt').Strategy; 
var User                =require('../app/models/user');
var config            =require('../config/database');

module.exports=function(passport){
      var opts = {}; 
  opts.secretOrKey = config.secret;
  passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.id}, function(err, user) {
          if (err) {
              return done(err, false);
          }
          if (user) {
              done(null, user);
          } else {
              done(null, false);
          }
      });
  }));
};

app.js

apiRoutes.post('/signup', function(req, res) {
  if (!req.body.name || !req.body.password) {
     res.json({success: false, msg: 'Please pass name and password.'});
         } else {
                var newUser = new User({
                                 name: req.body.name,
                                 password: req.body.password
                         });
    // save the user
        newUser.save(function(err) {
         if (err) {
                 return res.json({success: false, msg: 'Username already exists.'});
                }
                res.json({success: true, msg: 'Successful created new user.'});
                });
             }
        });

当我运行此代码时显示错误 -

throw "No callback function was given".

No Callback function was given

请帮我修复此代码。 感谢

1 个答案:

答案 0 :(得分:24)

bcrypt.hash()需要4个参数:

hash(data, salt, progress, cb)

文档不明确:它指出datasaltcb是必需的,这意味着progress不是,但没有它你会收到错误。

如果您不关心跟踪进度,请传递null

bcrypt.hash(user.password, salt, null, function (err, hash) { ... })