TypeError:使用Passport.js时无法读取未定义的属性“ headersSent”

时间:2018-06-26 09:01:44

标签: javascript node.js passport.js

app.js

var adminRouter = require('./routes/adminportal/home');
    app.use('/portal/admin', adminRouter)(passport);
    module.exports = app;

passport.js

var LocalStrategy   = require('passport-local').Strategy;

var mysql = require('mysql');
var dbconfig = require('../routes/db.js');


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


    passport.deserializeUser(function(id, done) {
        db(function(err,conn){
            conn.query("SELECT * FROM admin WHERE id = ? ",[id], function(err, rows){
                done(err, rows[0]);
            });
        })
    });


    passport.use(
        'local-login',
        new LocalStrategy({

            usernameField : 'user_name',
            passwordField : 'password',
            passReqToCallback : true 
        },
        function(req, username, password, done) {
            db(function(err,conn){
                conn.query("SELECT * FROM admins WHERE email_address = ?",[username], function(err, rows){
                    if (err)
                    return done(err);
                if (!rows.length) {
                    return done(null, false, req.flash('loginMessage', 'bulunamadi.')); 
                }


                if (password != rows[0].password)
                    return done(null, false, req.flash('loginMessage', 'yanlis parola.'));


                return done(null, rows[0]);
                })
            }) 
        })
    );

    module.exports = passport;

home.js

module.exports = function(passport){
  /* GET home page. */
router.get('/', function(req, res, next) {
  if(req.session.userId != null){
    message = '';
    //res.render('dashboard',{message:message});
    res.render("adminportal/login.ejs");
  }else{
    var message = '';
    var sess = req.session; 
    res.render('adminportal/login.ejs',{message:message});   
  }
});
return router;
}

因此,每当我尝试运行localhost5000:/portal/admin时,它将返回以下错误:TypeError: Cannot read property 'headersSent' of undefined

我被困住了,试图尝试实施长达数小时的passport.js,这是我第一次设置Passport.js。我做错了吗?我试图用Google搜索该错误,但没有相关结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

passport 参数应与require函数一起使用,而不是app.use()函数,这样app.js文件中的代码将为:

var adminRouter = require('./routes/adminportal/home')(passport); app.use('/portal/admin', adminRouter); module.exports = app;