Node.js:Express + RedisStore,req.session未定义 [英] Nodejs: Express + RedisStore, req.session undefined

查看:89
本文介绍了Node.js:Express + RedisStore,req.session未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前已经做过这件事……这次我没有遵循我做错的事情,但是我已经挣扎了几个小时,现在觉得自己精神错乱了。相应的代码:

I have done this before... I don't follow what I'm doing wrong this time, but I've been struggling for a couple of hours and now consider myself mentally blocked. The corresponding code:

app.use(express.bodyParser());
app.use(i18next.handle);
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'swig');
app.set('view cache', false);
var session_store = new RedisStore({ client : redis_client});
app.use(express.errorHandler({ dumpExceptions : true, showStack : true}));
app.use(express.cookieParser());
app.use(express.session({ store : session_store, secret : SESSION_SECRET, key : "sid" }));
app.use(app.router);

然后在处理请求时,这里只是一个例子:

Then when handling requests, here's just an example:

app.get('/session_test', function (req, res, next) {
  console.log(req.session); //undefined
});

与redis的连接正常。没有显示错误。然后,当尝试从请求访问它时,req.session是未定义的。浏览器正在发送正确的sid。

Connection to redis is working just fine. No errors are shown. Then, when trying to access it from the request, the req.session is undefined. The browser is sending the correct sid.

对于请求期间发生的确切流,我不是专家,但是在调试之后,好像路由器在

I'm no expert on the exact flow that occurs during the request, but after debugging, it seems as if the router was being called before the session middleware.

在此先感谢您提供所有可能的帮助。我会提供所有可能的代码,不确定您的帮助是什么。

Thanks in advance for any and all the likely help. I will provide any code I can, I'm unsure what might be of your help.

这里有更多代码。
server.js

Here's more code. server.js

  //Dependency modules
var express = require('express'),
  app = express.createServer(),
  //Application dependency modules
  settings = require('./settings'), //app settings
  routes = require('./routes'), //http routes
  rtroutes = require('./rtroutes'); //real time communication routes (io)

var io = require('socket.io').listen(app);
var appWithSettings = settings.setup(io, app);

routes.settings.setup(appWithSettings);
rtroutes.settings.setup(io, appWithSettings);

在调用route.settings.setup之前,不会添加任何路由。设置(这是全局设置)是一个很大的文件。完成所有配置的地方。直到也调用settings.setup方法时才添加设置。这是文件的一部分:

No routes are added until routes.settings.setup is called. settings (which is the global settings) is a pretty big file. That's where all configuration is done. Settings are not added until settings.setup method is called too. Here's a cut of the file:

//Dependency modules
var express = require('express'),
  redis = require('redis'),
//Important configuration values
var SESSION_SECRET = 'some secret thing which doesnt belong to stackoverflow!',
    insert_other_variables_here = "lalala";

//Computed general objects

var RedisStore = require('connect-redis')(express),
  redis_client = redis.createClient(REDIS_PORT, REDIS_HOST);

exports.setup = function (io, app) {
  app.configure(function () {
    app.use(express.bodyParser());
    app.use(i18next.handle);
    app.use(express.methodOverride());
    app.use(express.static(__dirname + '/public'));
    app.set('views', __dirname + '/views');
    app.set('view engine', 'swig');
    app.set('view cache', false);
    var session_store = new RedisStore({ client : redis_client});
    app.use(express.errorHandler({ dumpExceptions : true, showStack : true}));
    app.use(express.cookieParser());
    console.log("ABOUT TO ADD SESSION STORE MIDDLEWARE");
    app.use(express.session({ store : session_store, secret : SESSION_SECRET, key : "sid" }));
    console.log("AND NOW ADDED THE SESSION STORE MIDDLEWARE");
    app.use(app.router);
  });

  app.configure('development', function () {
     //some things in here, but nothing that affects app. I have commented this
     //for debugging and it changed nothing
  });

  app.configure('production', function () {
    //mostly configuration for io and some caching layers, as well as servers info
    app.use(express.errorHandler());
    app.use(express.logger({ stream : logFile }));
  });
  app.listen(WEB_PORT);
  return {
    app : app,
    //some other stuff that isn't relevant
  }
}

我将25条路由分为4个不同的文件(不知为何到目前为止我不需要会话,因为我延迟了某些部分,所需的一切都是用猫鼬做)。这是一个使用假名称的示例:

I have 25 routes split in 4 different files (somehow I didn't have a need for session until now, since I was delaying some parts and everything needed was done with Mongoose). Here's an example of how it is being done (with fake names):

routes / index.js

routes/index.js

export.settings = require("./settings");

routes / settings.js

routes/settings.js

exports.setup = function (app_settings) {
  require("./route1")(app_settings);
  require("./route2")(app_settings);
  require("./route3")(app_settings);
};

这是一个剥离的 route1文件( routes / route1.js):

Here's a stripped out "route1" file ("routes/route1.js"):

module.exports = function (app_settings) {
  var app = app_settings.app;
  console.log("ABOUT TO ADD ROUTES")
  app.get("/signin", function (req, res, next) {
    console.log(req.session); //this will be undefined
  });
  app.get("/register", function (req, res, next) {
  });
  app.get('/language', function (req, res, next) {
  });
  app.post('/settings', function (req, res, next) {
  });
  console.log("ADDED ROUTES NOW!")
}


推荐答案

无论何时定义路由,路由器都会自动插入到当时的中间件堆栈中(随后将其故意插入的尝试将被忽略)。在确定会话处理程序之前,确定要定义任何路由吗?

Whenever you define a route, the router gets automatically inserted into whatever the middleware stack is at the time (subsequent attempts to insert it deliberately will be ignored). Are you sure you aren't defining any routes before you set the session handler?

这篇关于Node.js:Express + RedisStore,req.session未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆