Friday, July 8, 2022

node.js: express: req.session returns "undefined"

 

>PROBLEM

node.js: express: req.session returns "undefined".

console.log(req.session)

- Returns:

undefined


>SOLUTION

The session block declaration shall come before the routing blocks.


>>BEFORE

// error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

// ...

const session = require('express-session');
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: ConfigSvc.configValue('sessionKey'),
    saveUninitialized:true,
    cookie: { maxAge: oneDay, secure: true },
    resave: false
}));


>>AFTER

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var todoRouter = require('./routes/todo');

var app = express();

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var favicon = require('serve-favicon');
const ConfigSvc = require('./utils/ConfigSvc');
app.use(favicon(__dirname + '/public/favicon.ico'));

const oneDay = 8640000;
const session = require('express-session');
app.set('trust proxy', 1) // trust first proxy
app.use(session({
    secret: ConfigSvc.configValue('sessionKey'),
    saveUninitialized:true,
    cookie: { maxAge: oneDay, secure: true },
    resave: false
}));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/todo', todoRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});


// error handler
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});


>ENV

Node.js 16
Express
JWT

No comments:

Post a Comment

eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...