7

I'm trying to set up a basic session system in node. Here's what I've got so far:

app.js:

app.use(express.cookieParser('stackoverflow'));
app.use(express.session());

I'm setting the session data in ajax.js:

addClassToCart: function(req, res) {
  req.session.cart = req.body.classId;
  console.log(req.session.cart);
}

This logs the correct information. However, when I try to retrieve that information elsewhere (same file, different function):

console.log(req.session.cart);

I get undefined. I feel like I'm missing something incredibly basic. Various tutorials for this are either awful or require me to add in even more packages (something I'm trying to avoid).

More data from my debugging:

  • This works with non-AJAX requests
  • The session is set before it's logged.
SomeKittens
  • 38,868
  • 19
  • 114
  • 143

4 Answers4

7

As it turns out, the issue wasn't with Express' session (as the other answers seem to think). Rather, it was a misunderstanding on my part. I changed addClassToCart to the following:

addClassToCart: function(req, res) {
    req.session.cart = req.body.classId;
    console.log(req.session.cart);
    res.send('class added');
  }

Adding res.send() fixed the problem.

SomeKittens
  • 38,868
  • 19
  • 114
  • 143
3

As noted in the answer to a related SO question, this can also occur if you're using fetch to get data from your server but you don't pass in the credentials option:

fetch('/addclasstocart', {
    method: 'POST',
    credentials: 'same-origin' // <- this is mandatory to deal with cookies
})

Cookies won't be passed to the server unless you include this option which means the request's session object will be reset with each new call.

Community
  • 1
  • 1
Chase Sandmann
  • 4,795
  • 3
  • 30
  • 42
-1

I don't know about basic session store, but redis only took me a few minutes to setup:

  app.use(express.session({
    store: new RedisStore({
      host: cfg.redis.host,
      db: cfg.redis.db
    }),
    secret: 'poopy pants'
  }));

On a mac:

brew install redis
chovy
  • 72,281
  • 52
  • 227
  • 295
-2
app.use(express.session({
  secret: "my secret",
  store: new RedisStore,
    cookie: { secure: false, maxAge:86400000 }
}));

Not sure the problem is in session age, but it just to be safe, I'd suggest you to specify maxAge.

f1nn
  • 6,989
  • 24
  • 69
  • 92
  • This requires me to add `Redis`. I've explicitly said in the question that I don't want to install new packages. – SomeKittens Nov 17 '12 at 19:26