Saturday 11 March 2017

req.session is undefined express-session

I know this question has been asked several times. However, none of the answers I've read has solved my question.

Many of them were outdated for express v4, as express-session is currently a separate module. Those question/answers are here:

Other questions are updated, however the solution given doesn't fix my problem. Those question/answers are here:

Most of the solutions are the sequence of middlewares when configuring the app. I've tried different options and I doesn't find the correct way to do it. Maybe it's just that.

In other solution, someone says that session middleware cannot be called, because if it were, req.session would be defined. I've used middlewares just before an after app.use(session({...})), and checked that both get called.

I've also found in this issue someone saying that he gets req.session undefined when the store disconnects. I'm using the default store so far. Could this be the problem?

I'm getting this error:

TypeError: Cannot read property 'destroy' of undefined

It breaks just when I try to logout a session with req.session.destroy() at login.js (see code below)


My code

server.js

const express = require('express');
const session = require('express-session');
const mongo = require('mongodb');
const passport = require('passport');
const path = require('path');
const routes = require('./app/routes');
const login = require('./app/routes/login.js');

const app = express();
app.use(session({
  secret: 'key',
  resave: false,
  saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/public', express.static(path.normalize('./public')));
app.use(routes);
app.use(login);
app.set('view engine', 'pug');

const MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://localhost:27017/myapp')
.then((db) => {
  // Link the database through the app. It will be available in the req.app object
  app.db = db;
  console.log('App listening on port ' + process.env.PORT);
  app.listen(process.env.PORT);
})
.catch((err) => {
  console.log('There was an error connecting to the database.');
  console.log(err);
});

module.exports = app; // For testing

login.js

const express = require('express');
const passport = require('passport');
const router = new express.Router();

// Other login logic here

router.get('/logout', (res, req) => {
  req.session.destroy((err) => {
    req.redirect('/');
  });
});

module.exports = router;



via dgrcode

No comments:

Post a Comment