node.js – 如何修复:Nodejs passport.header问题,req.session.passport undefined

我目前在我的开发服务器中遇到此错误.这在登录尝试时发生:

这是护照特有的问题吗?请帮助,这在生产服务器中非常有效

我在我的app.js中有这个

app.use(cookieParser('12345678'));
app.use(session({ secret: '12345678', resave: false, saveUninitialized: true })); 
app.use(validator());
app.use(passport.initialize());
app.use(passport.session()); 
app.use(flash()); // flash - Initializing
app.use(compression()); 
app.use('/app', express.static(path.join(__dirname, '/app'), { maxAge: 7 * 86400000 }));
app.use('/uploads', express.static(path.join(__dirname, '/uploads'), { maxAge: 7 * 86400000 }));
app.set('view engine', 'pug');
app.locals.pretty = false;
app.set('views', './views');
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

然后在auth方法中

module.exports = function (passport) {

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

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

    passport.use('site-register', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'pwd',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },

    function (req, email, pwd, done) {
            process.nextTick(function () {

            if( condition is ok){
                  return done(null, user, { message: 'Login Success' });
            }else{
              return done(null, false, { message: 'Invalid Login, Please try another method to login' });
        }
   ));


   .....
}

然后问题:

embah@devsertwo:~/node/nodeapp$node app
Server turned on with development mode on port 3002
/home/embah/node/nodeapp/routes/auth.js:384
                                    req.session.passport.header = authHeader;
                                                                ^

TypeError: Cannot set property 'header' of undefined
    at /home/embah/node/nodeapp/routes/auth.js:384:65
    at /home/embah/node/nodeapp/controller/adaptor/mongodb.js:31:9
    at Query.<anonymous> (/home/embah/node/nodeapp/node_modules/mongoose/lib/quer
y.js:2180:28)
    at /home/embah/node/nodeapp/node_modules/kareem/index.js:177:19
    at /home/embah/node/nodeapp/node_modules/kareem/index.js:109:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
embah@devsertwo:~/node/nodeapp$Write failed: Connection reset by peer

console.log(req.session)返回下面

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }

似乎护照从未添加过

最佳答案 事实上,相同的代码在一个环境中工作但在另一个环境中工作,这让我相信这是一个环境或配置问题.

也许某些软件包版本之间的不兼容性因生产与开发而异?尝试更新所有依赖项,看看是否有任何变化.

有时,改变中间件的顺序也会有所帮助.

点赞