I can't understad what is wrong with my code using the expressjs sessions.
I am settingreq.session.is_logged = true on a route /login, then press F5 which calls the route /session and the value of req.session.is_logged is false on it.
Here is some code
var express = require("express");
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'test', store: express.session.MemoryStore({
reapInterval: 60000 * 10
})}));
});
app.get('/session', function(req, res){
if (req.session.is_logged){
console.log('|-->Session recognized');
res.status(200);
res.send({ response: "OK" });
}else{
console.log('|-->Any session recognized');
res.status(403);
res.send({ response: "KO" })
};
});
app.get('/login', function(req, res){
req.session.is_logged = true;
res.status(200);
res.send({ response: "OK" });
});
app.listen(3000);
I saw some similar way to do it and it seems to work... Thanks for your help !
Express v3.0.5
You probably don't respect the same origin policy, the session system doesn't support the CORS.
Your code is not wrong, but if you visit the URL mydomain.com and reach your node server on mydomain.com:3000 it can't work.
There are many ways to make it works (Apache proxy reverse, NGINX...), make some research and take the most appropriate in your case.
you are setting req.session.is_logged = false on /login route so how can it be true..
The more better way to use memory store for session is
var MemoryStore = express.session.MemoryStore
,store = new MemoryStore();
app.use(express.session({ secret: 'something', store: store }));
The problem is you're not sending a response with your login route, so the client doesn't know to set a cookie. The fix is to simply send any response:
app.get('/login', function(req, res){
req.session.is_logged = true;
res.send('Ok!'); /* Now the 'Set-Cookie' HTTP header will be sent to the client. */
});
And make sure you're referencing the MemoryStore object correctly as an attribute of express.session since it's not a global object:
app.use(express.session({secret: 'test', store: express.session.MemoryStore({
reapInterval: 60000 * 10
})}));