0

I'm new to node.js and sessions, I'm trying to store some values in the node.js session, but everytime I reload the page and check the console.log the session haven't been saved. My code:

var session;
var org;

function checkSession(argument){
  var sess = argument;
  if(sess.org){
    return null;
  }
  else{
    return sess.org;
  }
}
/* GET home page. */
router.get('/', function(req, res, next) {
  session = req.session;
  var sessionChecked = checkSession(session);
  if(sessionChecked){
    org = sessionChecked;
  }
  else{
    org = req.query.org || 'Google';
    session.org = org;
    session.save();
  }

So basically what I want is, when the user loads the page for the first time, he can type a organization, and when he does that, this organization is saved on the session, so when he reloads the page, the organization is already selected.

I know I must be doing something really wrong and/or bad codding, but I just can't figure this out.

Thank you!

Pablo
  • 510
  • 8
  • 22

2 Answers2

1

It looks like calling session.save() isn't doing what you expect. Express won't write to the session unless the route is fully processed. You likely need to call res.end() at the end of your get function.

Take a look at https://github.com/expressjs/session#reqsession and try to understand each line of code in that example.

Good luck!

Armando Canals
  • 290
  • 1
  • 7
  • Thanks for the reply, but it seems that I can't do that because I'm already rendering the body, so I get this error "Can't set headers after they are sent". This demo code seems to be using the same logic as mine, so I have no idea what I'm doing wrong – Pablo Sep 23 '15 at 07:13
  • I don't see that from the code example you posted. Perhaps try to remove the call to `save()` altogether as Express will automatically save the session data *if* the route is completed. It also might be possible that you are returning the body before you set the session information, but I don't see that in your code. – Armando Canals Sep 23 '15 at 07:26
  • Thank you! So this is my index.js: http://pastebin.com/uqSKV1Ms And this is my app.js: http://pastebin.com/bhqTm96L – Pablo Sep 23 '15 at 07:48
0

It turns out the problem was that my session was expiring in 20 seconds. Silly me.

Pablo
  • 510
  • 8
  • 22