k.k k.k - 3 months ago 16
Node.js Question

how to use express Session

I am a express freshman, I have a problem with session now. this code I can't store seesion. req.session.user is undefined, maybe the quession was the session not store. what's wrong of my code, please tell me my wrong please thanks

var express = require('express');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(expressSession({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
var auth = function(req, res, next) {
console.log(req.session.user); **this is undefined**
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amyspassword") {
req.session.user = "amy";
req.session.admin = true;
res.send(req.session.user);
}
});
app.get('/logout', function (req, res) {
req.session.destroy();
res.send("logout success!");
});
app.get('/content', auth, function (req, res) {
res.send("You can only see this after you've logged in.");
});
app.listen(3000);

Answer

Instead of the current code you have for using express session try the following code.

app.use(expressSession({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true
}));

secure: true although a recommended option requires an https-enabled website. HTTPS is necessary for storing secure cookies. If you set that option to true while using an HTTP only site without HTTPS the cookie will not be set which is why you were running into problems. The GitHub repo for express-session has some more detail regarding this.

So changing your code to that should work. Let me know if that doesn't make sense or if it still gives you problems.

EDIT

Try also the following line of code inside your get /login route from:

res.send(req.session.user);

To this:

res.redirect('/content');

EDIT 2

To not have it automatically redirect but still save the session try the code below.

req.session.save();
res.send("test");
Comments