Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change and refresh session data in Node.js and express-session

I'm using Node.js along with express-session and I've got this session data that holds the user information

req.session.user

now when the user updates the information, I set the session to the new data and then reload it

req.session.reload(function(err) {
req.session.user = user;
});

it should work but the req.session.user still shows the old information, why? :(
many thanks in advance

like image 776
Mohsen Shakiba Avatar asked Feb 13 '15 15:02

Mohsen Shakiba


1 Answers

You are reloading before saving your change. Saving usually happens at the end of the request automatically. There is a test in session.js which demonstrates that behaviour.

Using req.session.reload() reverts the changes that currently have been been made while processing the request ...

req.session.example = 'set on set_reload'
req.session.reload( function (err) {
    res.render('index', { title: req.session.example });
});
// next http get request
// req.session.example == value before the call above 

Consider using the session like this

req.session.example = 'set on set';
res.render('index', { title: req.session.example });
// next http get
// req.session.example == 'set on set'

If you have a real reason for using req.session.reload() then this type of usage will give you the desired behaviour

req.session.example = 'set on set_save_reload';
req.session.save( function(err) {
    req.session.reload( function (err) {
         res.render('index', { title: req.session.example });
    });
});
// next http get
// req.session.example == 'set on set_save_reload'
like image 52
Christopher Hackett Avatar answered Nov 03 '22 01:11

Christopher Hackett