【发布时间】:2012-01-10 19:53:33
【问题描述】:
我(几乎)成功地将 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 } }
很明显,“用户名”对象已经消失了。会话没有保留它,只是重建了一个新的。
我该如何解决这个问题?如果您需要任何信息,请不要犹豫。
这是我设置会话管理的代码:
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(忽略渲染视图的属性)
【问题讨论】:
-
能否将代码粘贴到包含 Redis 会话存储的位置?那里有一个超时选项,可能你不小心把它设置得太低了。
-
已添加 :) 设置为 60 秒,我显然不使用 60 秒来编写凭据...
-
我认为这是一个小项目,我认为最好将其发布在某个地方(要点,粘贴)并提供链接。我敢打赌,错误出在您未粘贴的代码中。 (只是猜测)
-
最后添加了要点链接
-
@Florian 我投票给你。这是我能为你做的最多的事情:-)