node.js - Session data is not saving to memory while using express-session -



node.js - Session data is not saving to memory while using express-session -

i encountering problem when seek next illustration using different express-session versions.

using express-session 1.0.2:

var connect = require('express'), cookieparser = require('cookie-parser'), session = require('express-session'); var app = connect(); app.use(cookieparser()) .use(session({secret:'sessionsecret',cookie:{maxage:60000}})) .use(function(req,res,next){ if(req.session.views){ res.setheader('content-type','text/html'); res.write('<p>views ' + req.session.views + '</p>'); //here res.end(); req.session.views++; } else { req.session.views = 1; res.end('welcome demoe. seek refresh page'); } }) .listen(3000);

this works; view counter keeps increasing when refresh page. however, when alter express-session 1.8.2 (the latest), code ceases work , view counter stays @ 1. after modify code following, works again:

var connect = require('express'), cookieparser = require('cookie-parser'), session = require('express-session'); var app = connect(); app.use(cookieparser()) .use(session({secret:'sessionsecret',cookie:{maxage:60000}})) .use(function(req,res,next){ if(req.session.views){ res.setheader('content-type','text/html'); res.write('<p>views ' + req.session.views + '</p>'); //here req.session.views++; res.end(); } else { req.session.views = 1; res.end('welcome demoe. seek refresh page'); } }) .listen(3000);

it seems session info saving before response sent in new express-session. can explain this?

yes, expressjs sessions cannot save req.session object after res.end() called - or content info sent.

the reason because cookies can set (therefor session can saved) when headers beingness sent; after headers sent (and content sent), cookie cannot reset , session cannot saved.

you can see code in action here.

node.js session

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -