Node.js - 会话不会通过res.redirect()持久存在

时间:2011-12-01 16:59:57

标签: node.js redis express

我(几乎)成功地使用带有Express和Redis的Node.js来处理会话。

我遇到的问题是当我使用res.redirect()时,会话不会被保留。

以下是我如何看待它:

req.session.username = username.toString();
console.log(req.session);
res.redirect('/home');

console.log()打印:

{ lastAccess: 1322579131762,
  cookie:
   { path: '/',
     httpOnly: true,
     _expires: Tue, 29 Nov 2011 15:06:31 GMT,
     originalMaxAge: 60000 },
  username: 'admin' }

现在,这是以下代码:

app.get('/home', [app.requireLogin], function(req, res, next) {
// Not showing the rest as it's not even getting there
// Instead, here is what's interesting
app.requireLogin = function(req, res, next) {
  console.log(req.session);

这个console.log()打印出来:

{ lastAccess: 1322579131775,
  cookie:
   { path: '/',
     httpOnly: true,
     _expires: Tue, 29 Nov 2011 15:06:31 GMT,
     originalMaxAge: 60000 } }

显然,'username'对象已经消失。会议没有保留它,只是重建了一个新的。

我该如何解决这个问题?如果您需要任何信息,请不要犹豫。

以下是我设置会话管理的代码:

app.configure(function() {
  // Defines the view folder and engine used.
  this.set('views', path.join(__dirname, 'views'));
  this.set('view engine', 'ejs');

  // Allow parsing form data
  this.use(express.bodyParser());

  // Allow parsing cookies from request headers
  this.use(express.cookieParser());
  // Session management
  this.use(express.session({
    // Private crypting key
    secret: 'keyboard cat',
    store: new RedisStore,
    cookie: {
      maxAge: 60000
    }
  }));
  this.use(app.router);
});

这是整个项目(我的意思是,它的一部分),在要点上:https://gist.github.com/c8ed0f2cc858942c4c3b(忽略渲染视图的属性)

5 个答案:

答案 0 :(得分:6)

好吧,我找到了解决方案。问题是maxAge中的时间已添加到当前日期。因此,在浏览器端,cookie被设置为在显示的GMT时间到期。

问题如下:我使用虚拟机来测试node.js,你知道......有时,你暂停你的机器。

嗯,发生的事情是机器的时间晚了两天。因此,无论何时在服务器端设置cookie,客户端都认为cookie已经过期,因为我的主机迟了两天。

另一个愚蠢的结果。

答案 1 :(得分:2)

你尝试过不同的浏览器吗?您是否在页面重定向之间保持相同的会话ID?

您可以在重定向...

之前添加req.session.cookie.expires = false;

答案 2 :(得分:1)

您的代码看起来非常可靠,但是您有使用client.end()的原因吗?它强行关闭redis连接并且不干净。我认为你根本不需要它:

https://github.com/mranney/node_redis/issues/74

我不确定connect-redis的底层架构,但我想知道调用client.end是否正在重置你的会话。如果你拿出来会怎么样?

答案 3 :(得分:1)

我遇到了类似的问题,因为我在会话中设置的内容并未在app.get()设置的位置之外保留。

我的问题原来是我 res.redirect()结尾处app.get()做了 。看起来我在请求对象上设置了一些东西,然后允许它收集垃圾。

我添加了res.redirect( '/nextmethod' ),数据仍然存在。

答案 4 :(得分:0)

当然,您需要以某种方式保存该会话,这可能会有效。

req.session.regenerate(function(){
    req.session.username = username.toString();
    res.redirect('/home');
});
相关问题