问题
I've tried many ways of setting the session variables but have been unsuccessful in finding a solution. The problem more precisely is that the session (custome) variables are not being passed to other routes (so they aren't being stored in the default MemoryStore presumably). All of the code is available at https://github.com/codexa/pictroid/blob/session/app.js
This is the portion of code for assigning the session variable (https://github.com/codexa/pictroid/blob/session/app.js#L304-311)
console.log(req.session);
req.session.regenerate(function(){
// Store the user's primary key
// in the session store to be retrieved,
// or in this case the entire user object
req.session.user = "some user";
req.session.auth = true;
});
I'm aware of the fact that this is async and the proceeding code will be executed while this does but making it synchronous doesn't solve the problem.
As an example, I'm trying to retrieve the custom "req.session.user" in the root dir route (https://github.com/codexa/pictroid/blob/session/app.js#L87-L88)
app.get('/', function(req, res) {
console.log(req.session.auth);
...
So can anyone please tell me what I'm doing wrong and how to solve it? Thanks in advance.
回答1:
You should not set secure: true if you are using http because cookies with secure: true will only be sent for https requests. If you want to keep secure: true, you will need to start an https server instead. If you are doing this only for development purposes, then you can just temporarily remove secure: true until you put your code into production (where you use https).
Also on an unrelated note, you can avoid regenerate() and the session fixation problem by only starting a session after a successful authentication and for authenticated routes. This will also help decrease the number of sessions in your session store from visitors who never sign in or crawlers (unless of course you need to store session data for unauthenticated users).
来源:https://stackoverflow.com/questions/23839085/session-variables-not-being-set-in-expressjs