node.js - 错误 : passport. 初始化()中间件未使用 |在数据库中创建用户但出现此错误

标签 node.js express passport.js passport-local

我正在尝试让用户注册我的应用程序,当我这样做时,它会在控制台中显示错误 错误:passport.initialize() middleware not in use 但我确实有 Passport 已初始化。但它确实在数据库中正确创建了用户。看来最初的 Passport 设置是错误的。

我已经包含了我认为应用程序的重要部分来解释正在发生的事情。我在堆栈跟踪指向的行添加了注释。

App.js

app.use(session({
    secret: config.sessionSecret,
    // create new redis store.
    store: new RedisStore({ host: 'localhost', port: 6379, client: client, auto_reconnect: true}),
    saveUninitialized: false,
    resave: false,
    cookie: {
        maxAge: 60 * 1000 * 60 * 24 * 30 // 30 days
    },
}));

// PASSPORT CONFIGURATION
require('./controllers/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());

// Routes
require('./routes/index.js')(app, passport);

controllers/passport.js

passport.use('signup', new LocalStrategy({
      usernameField: 'email',
      passReqToCallback : true
    },
    function(req, email, password, done) {
        User.findOne({ email: req.body.email }, function(err, existingUser) {
          if(err){
            console.log(err);
          }
          if (existingUser) {
            req.flash('form', {
              email: req.body.email
            });
            return done(null, false, req.flash('error', 'An account with that email address already exists.'));
          }

          var user = new User({
            email: req.body.email,
            password: req.body.password 
          });

          user.save(function(err) {
            if (err) return done(err, false, req.flash('error', 'Error saving user.'));

            var token = new Token({ _userId: user._id, token: crypto.randomBytes(16).toString('hex') });
            token.save(function (err) {
            if (err) return done(null, false, req.flash('error', err.message));
            var email = req.body.email;
            // Send the email for the token
            var message = 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + token.token + '\/' + email + '\n';
            sendEmail('"APPNme" noreply@example.com', user.email, 'Account Verification Token', message);
            });
            var time = 14 * 24 * 3600000;
            req.session.cookie.maxAge = time; //2 weeks
            req.session.cookie.expires = new Date(Date.now() + time);
            req.session.touch();
            return done(null, user, req.flash('success', 'A verification email has been sent to ' + user.email + '.')); // stack trace points to this line as the error line. 
          });
        });

    })
  );

routes/index.js

app.post('/signup', passport.authenticate('signup', {
    successRedirect : '/profile', section
    failureRedirect : '/signup',
    failureFlash : true 
}));

最佳答案

您需要添加passport.initialize中间件。
引用:https://scotch.io/tutorials/easy-node-authentication-setup-and-local

// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

需要维持的顺序:

文档

  • body解析器
  • 快速 session
  • 需要passport.js
  • Passport .初始化
  • Passport . session
  • 需要路线

关于node.js - 错误 : passport. 初始化()中间件未使用 |在数据库中创建用户但出现此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696191/

相关文章:

javascript - 无法在 Sequelize 中使用类模型在数据库中创建表

javascript - 自定义模块express js :Cannot find module name error when modules folder in root directory

node.js - 使用node.js、express、socket实现通知系统

node.js - 类型错误 : Cannot read property 'map' of undefined in reactjs

javascript - Node js Next 不是 Passport 策略错误中的函数

javascript - Passport.js 回调总是出错

node.js - 在 express 中,我如何将用户重定向到外部网址?

node.js - aws 内核正在杀死我的 Node 应用程序

node.js - 使用强大的 Node 文件上传不起作用

node.js - 是否可以通过 Restful 服务使用 Facebook 帐户登录某人?