我使用express.js和React。成功登录后,我将user_id
存储在会话中,但在2-3分钟会话丢失后,当我刷新页面时,他们会退出我。
这是我的server.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host',
user : 'user',
password : 'password',
database : 'database',
pool : { maxConnections: 50, maxIdleTime: 30},
});
connection.connect(function(error){
if(!!error){
console.log('error');
}else{
console.log('Connected');
}
})
//pluginy
var bodyParser = require('body-parser');
var express = require('express');
var session = require('express-session');
var app = express();
//ustwienia
app.use(bodyParser()); //przesylanie danych w req.body
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'v8bRRj7XVC6Dvp',
saveUninitialized: true,
resave: true,
cookie: {secure: true}
}));
app.use('/static', express.static(__dirname + '/src'));
app.use('/dist', express.static(__dirname + '/dist'));
app.use('/php', express.static(__dirname + '/php'));
app.set('views', __dirname + '/views');
app.set('view engine','pug');
function checkAuth(req, res, next) {
console.log('User id: '+req.session.user_id);
if (!req.session.user_id) {
if(req.route.path=='/'){
res.render("indexNotLogin",{title:''});
}else{
res.send('You are not authorized to view this page');
}
} else {
next();
}
}
//roots
//index
app.get('/', checkAuth, function(req, res){
res.render("index",{title:''});
})
//funkcje
app.get('/funkcje', function(req, res){
res.render("funkcje",{title:''});
})
//trylogin
app.post('/trylogin', function(req, res){
var username = req.body.name;
var password = req.body.password;
connection.query("SELECT * FROM user WHERE username='"+username+"' AND pass='"+password+"' LIMIT 1", function(error, rows,fields){
//callback
if(!!error){
console.log('error in query');
}else{
if(rows.length){
console.log(rows[0].id)
req.session.user_id = rows[0].id;
res.redirect('/');
}else{
res.send('user dont exist')
}
}
})
})
app.listen(3000,'0.0.0.0', function(){
console.log('Port: 3000')
})
在表单提交后我执行功能/trylogin
并且eveything工作正常,req.session.user_id = rows[0].id
是user_id,但为什么会话丢失得这么快?
答案 0 :(得分:2)
您可以在会话中间件中使用maxAge
选项来增加会话时间:
app.use(session({
secret: 'v8bRRj7XVC6Dvp',
saveUninitialized: true,
resave: true,
cookie: {maxAge:900000} //here ,15 min session time
}));