使用NodeJS和Express 4.x的会话(req.session undefined)

时间:2015-07-24 13:33:30

标签: node.js session express login

首先抱歉我的英语不好。我正在学习,我正在做一个学术项目并遇到了一个问题。我记不起会话变量了。

的package.json

  "dependencies": {
    "body-parser": "^1.7.0",
    "ejs": "~1.0.0",
    "express": "^4.8.7",
    "express-session": "^1.11.3",
    "ini": "^1.3.4",
    "mysql": "^2.8.0",
    "winston": "^1.0.1"
}

server.js

var express = require('express');
var session = require('express-session');
var app = express();
...
require('./router/main')(app, language, connection, logger);

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(session({
    secret: 'pecuniamsekretsession',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

main.js

module.exports = function(app, languageItems, connection, logger) {
    app.post('/', require('../router/login.js')(languageItems, connection, logger)); 
    app.get('/', require('../router/login.js')(languageItems, connection, logger));
}

login.js

module.exports = function (language, connection, logger) {

    var routerTemplateLogin = function (req, res) {
        var utils = require('../utils/utils');
        var util = new utils.Util;  

        // It does not work  :-(
        logger.debug(req.session); 

        req.on('data', function(data) {
            var arrayPost = util.postDataToArray(data);
        });     

        res.render('pages/login.ejs', {
            lang: language
        });
    }

    return routerTemplateLogin;
}

在login.js中,请参阅// It does not work :-(https://github.com/braulioti/pecuniam

中的完整项目

由于

1 个答案:

答案 0 :(得分:6)

问题是路由是在任何其他中间件之前设置的。移动这一行:

require('./router/main')(app, language, connection, logger);

之后:

app.use(session({
    secret: 'pecuniamsekretsession',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

server.js