节点js会话注销问题

Node js session logout issue

我创建了一个 Node js 应用程序, 我正在使用

创建会话
app.use(session({
  resave: true , 
  rolling: true,
  secret: '2853554111' , 
  genid: function(req) { return uuid(); },
  saveUninitialized: true
 }));

这就是我在会话中保存数据的方式。

req.session.user=req.body.username;

但过了一段时间后,我在会话中得到了未定义的用户值,而且这种情况经常发生, 不确定代码有什么问题。

这就是我的 app.js 的样子

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);

您可以使用 express-sessionstore 属性将您的会话保存在数据库中。 link 中给出了多个示例。 下面是将节点 js 连接到 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,
 }));

一切顺利。