Node.js – 会话不会通过res.redirect()持续存在

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

我遇到的问题是,当我使用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 } } 

显然,“用户名”对象已经消失。 会议没有保留它,只是重build了一个新的。

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

这里是我设置会话pipe理的代码:

 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 (忽略渲染视图的属性)

好的,我find了解决办法。 问题是maxAge中的时间被添加到当前date。 所以,在浏览器端,cookie被设置为在显示的GMT时间到期。

问题是:我使用虚拟机来testingnode.js,而且,你知道…有时候,你暂停你的机器。

那么发生了什么事,机器的时间晚了两天。 所以,无论什么时候cookie被设置在服务器端,客户端认为cookie已经过期,因为我的主机迟了两天。

另一个愚蠢的结果。

你有没有尝试不同的浏览器? 你是否在页面redirect之间保持相同的会话ID?

你可以添加req.session.cookie.expires = false; 在redirect之前…

你的代码看起来非常稳定,但是你有使用client.end()的原因吗? 强行closuresredis连接,不干净。 我不认为你需要它:

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

我不确定connect-redis的底层架构,但我想知道是否调用client.end是什么重置您的会话。 如果你把这些拿出来会发生什么?

我遇到了一个类似的问题,因为我在会话中设置了一些不在app.get()之外的app.get()

我的问题原来是,我没有做我的app.get()结束app.get() 。 看起来我正在设置一个请求对象的东西,然后让它收集垃圾。

我添加了一个res.redirect( '/nextmethod' ) ,数据持续很好。

当然,你需要以某种方式保存会话,这可能工作。

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