Node.Js - Passport - Express Validator - req参数是Undefined

时间:2017-06-28 11:12:33

标签: node.js express

首先,我在我的路线中有这个,我需要使用Passport来验证用户注册过程:

router.post('/user/signup', passport.authenticate('local.signup',{
  successRedirect: '/user/profile',
  failureRedirect: '/user/signup',
  failureFlash: true 
}));

我正在从Youtube Video学习Node JS,在教程中,有一个步骤来创建名为“config”的文件夹,在“config”文件夹中,有一个名为“passport.js”的文件。

问题是,这个“passport.js”中的一个函数里面有“req”参数。当我尝试运行我的程序时,有一个错误,表示“req未定义”。这是“passport.js”的源代码:

var express = require('express');
var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;

passport.serializeUser(function(user, done){
  done(null, user.id);
});

passport.deserializeUser(function(id, done){
  User.findById(id, function(err, user){
    done(err, user);
  });
});


passport.use('local.signup', new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password',
  passReqToCallBack: true
}, function(req, email, password, done){ //here is the problem
  console.log('REQ :');
  console.log(req);
  console.log('password :');
  console.log(email);
  console.log('email :');
  console.log(password);
  console.log('done :');
  console.log(done);

  req.checkBody('email','Invalid Email').notEmpty().isEmail();
  req.checkBody('password','Invalid password').notEmpty().isLength({min:4});
  var errors = req.validationErrors();
  if(errors){
    var message = [];
    errors.forEach(function(error){
      message.push(error.msg);
    });
    return done(null, false, req.flash('error', messages));
  }
  
  User.findOne({'email': email}, function(err, user){
    if(err){
      return done(err);
    }
    if(user){
      return done(null, false, {message: 'Email is already in use.'});
    }
    var newUser = new User();
    newUser.email = email;
    newUser.password = newUser.encryptPassword(password);
    newUser.save(function(err, result){
      if(err){
        return done(err);
      }
      return done(null, newUser);
    });
  });
}));

如何使req填充passport.js中的参数?

1 个答案:

答案 0 :(得分:0)

该参数名为passReqToCallback,而不是passReqToCallBack(注意b必须是小写的。)