问题
I'm a bit new to sessions and now when I'm trying to use them the session is always undefined for me when coming to the next page after a successful login as an example.
If my login is successful I do the following
var session = req.session;
session.user_id = String(item._id);
session.user_secure = security.security(session.user_id);
Then I redirect to another page:
res.writeHead(302, {
'Location': '/backstageArea'
});
res.end();
And then I try to fin the session again doing this:
var session = req.session;
console.log("uid: " + String(session.user_id));
console.log("hid: " + session.user_secure);
which results in the session being undefined.
these are my last three things in my app.configure:
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', store: store, key: 'sid', cookie:{secure:true}}));
app.use(app.router);
Could it be since I'm redirecting to a new page that I loose the session? Or am I doing something else wrongly?
回答1:
By using cookie:{secure:true}
, you tell your express application and browsers to send that cookie over https only.
So if you don't use https
, you can remove secure: true
Secured cookies are useful feature to protect your sensitive cookies from mand-in-the-middle attack, They are much more useful when you use both http
and https
on the same domain.
If you want to use https on via nginx
or apache
, you may need:
app.set('trust proxy', true); // if remove this line, express will refuse to send https cookie to nginx or apache
回答2:
var session = req.session;
session.user_id = String(item._id);
session.user_secure = security.security(session.user_id);
edit to
req.session.user_id = String(item._id);
req.session.user_secure = security.security(session.user_id);
来源:https://stackoverflow.com/questions/20844743/connect-session-undefined-when-loading-new-page