I have created an Node js app, I am creating session using
app.use(session({
resave: true ,
rolling: true,
secret: '2853554111' ,
genid: function(req) { return uuid(); },
saveUninitialized: true
}));
and this is how I am saving my data in session.
req.session.user=req.body.username;
but after sometime I am getting undefined value of user in session, and this is hapenning very frequently, Not sure what is wrong with the code.
This is how my app.js looks like
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bodyParser = require('body-parser');
var uuid = require("uuidv4");
var app = express();
var login = require('./routes/login-admin');
var adminHome = require('./routes/adminHome');
var pmLogin = require('./routes/pmLogin');
var pmHome = require('./routes/pmHome');
var confirmEmail = require('./routes/confirmEmail');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static('public'));
app.use(logger('dev'));
//app.use(express.json());
app.use(express.json({limit: '5120mb'}));
//app.use(bodyParser.json())
app.use(bodyParser.json({ limit: '5120mb' }))
app.use(express.urlencoded({limit: '5120mb', extended: false }));
// view engine setup
app.use(session({
resave: true ,
rolling: true,
secret: '2853554111' ,
genid: function(req) { return uuid(); },
saveUninitialized: true
}));
app.use('/', indexRouter);
//app.use('/', login);
app.use('/users', usersRouter);
app.use('/login-admin', login);
app.use('/adminHome', adminHome);
app.use('/login', Login);
app.use('/Home', Home);
app.use('/confirmEmail', confirmEmail);
CodePudding user response:
you can use store
attribute of express-session
to save your session in database.
multiple example is given in this link.
Below is the snippet of connecting node js to Mysql
const MySQLStore = require('express-mysql-session')(session);
const options = {
host: "xx.xx.xx.xx", // setting connection options
user: 'node',
password: "xxxxxxxx",
database: 'xxxxx',
socketPath: 'xxxxx' //required only if using GAE
};
const sessionStore = new MySQLStore(options);
app.use(session({
resave: true ,
rolling: true,
secret: 'xxxxxx' ,
saveUninitialized: true,
cookie: { maxAge: 86400000 },
store: sessionStore,
}));
and you are good to go.