sessionsetcookie-session

cookie-session cannot set session


My question is about cookie-session. So I'm getting this problem after trying to deal with cookie-session. I cannot set any session. The problem is when im trying to set it req.session.login And this login is a problem but idk why

process.nextTick(function() { throw err; });
                              ^

TypeError: Cannot set property 'login' of undefined
at C:\Users\syriu\WebstormProjects\pubg\routes\login.js:30:35

This is my app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cookieSession = require('cookie-session');

var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var register = require('./routes/register');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', index);
app.use('/users', users);
app.use('/login', login);
app.use('/register', register);


app.use(cookieSession({
   name: 'session',
   keys: ['x', 'y']
}));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
    res.render('error');
  });

  module.exports = app;

And this is my login.js where is the problem

var express = require('express');
var router = express.Router();
var mongod = require('simple-mongod');
var UserManagement = require('user-management');

/* GET home page. */
router.get('/', function(req, res, next)
{
    res.render('login');
 });

router.post('/', function(req, res, next)
{

    var users = new UserManagement();
    users.load(function(err)
    {
        users.authenticateUser(req.body.login, req.body.pass,                                function(err, result)
        {
            if (!result.userExists)
            {
                console.log('Invalid username');
            }
            else if (!result.passwordsMatch)
            {
                console.log('Invalid password');
            }
            else
            {
               req.session.login = req.body.login;
                res.redirect('/users');
            }
            users.close();
        });
    });

});

module.exports = router;

Solution

  • You are adding the /login route first and then the cookie-session. This means, there is still no session when your request hits your custom login route. The session will be added to the request, but at a later time.

    app.use(cookieSession({
       name: 'session',
       keys: ['x', 'y']
    }));
    
    app.use('/', index);
    app.use('/users', users);
    app.use('/login', login);
    app.use('/register', register);
    

    You need to register the Cookie Session Middleware before the routes where you want to use it.