This is my code:
var express = require('express')
var sessionCookie = require('cookie-session')
var app = express();
app.use(sessionCookie({ keys: ['abc'], name: 'user' }));
app.get('/', function (req, res, next) {
req.session.views = (req.session.views || 0) + 1;
res.end(JSON.stringify(req.session));
console.log('req.session', req.session);
});
app.get('/logout', (req, res) => {
req.session = {};
// req.session = null;
console.log("req.session(logOut): ", req.session);
res.redirect('/');
});
app.listen(3000);
Why is the session not deleted when I use req.session = {}, but when I use req.session = null the session is deleted.
Take a look at the source code v2.0.0/index.js#L124
The
req.sessionhas a setter/getter function, see:When you set the
req.sessiontonullthesessvariable will be set tofalse. If you set an empty object{}toreq.session, as you can see, it will create a new session.At the end,
cookie-sessionwill use theon-headerspackage to set the cookie, if thesessisfalse, the cookie will be set to''.