0

I get undefined req.session, with the following code:

var express = require('express');
var app = express();

app.set('port', process.env.PORT || 3000);

app.use(express.static(__dirname + '/static'));
app.use(require('json-middleware').middleware());
app.use(require('express-session')(
     {resave: false,
      saveUninitialized: false,
      secret: 'secret',
      cookie: { secure:false, maxAge: 60000 }}
));

app.post('/api/logIn', function(req, res) {
    req.session.userName = req.body.userName;
    res.end('O.K.');
});

Obviosusly this is not true authentication but please ignore that since I can't find the reason for this error. Cookie-parser is not needed anymore since express-session v1.5 (it's use is discouraged). I still tried it but the error (unsurprisingly) persists.

  • You don't have a body parsing middleware included, meaning `req.body` will be undefined. – Ben Fortune Jun 12 '15 at 11:56
  • json-middleware should handle all JSON, other types are indeed not implemented but when I used body parser, node runtime informed me that this module is deprecated and that separate parsers should be used for every type, and I thought JSON parser will be enough... or is it. – Dalibor Dragojevic Jun 12 '15 at 12:02
  • `json-middleware` does absolutely nothing of the sort if you look at the [source](https://github.com/steveukx/json-middleware/blob/master/src/json-middleware.js). All it does is send JSON instead of a view if a JSON header is found when using `res.render`. The `body-parser` module is not deprecated, just one of the ways you used it. See [this answer](http://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4/24330353#24330353) – Ben Fortune Jun 12 '15 at 12:09
  • Thanks Ben Fortune, you were right I was using body parser on a wrong way. This solved the issue. – Dalibor Dragojevic Jun 12 '15 at 12:22

0 Answers0