I'm new to node.js and I'm stuck here. I have the following code in my router:
router.get('/', function(req, res, next) {
// Initialize the game
if(!req.session.gameStarted) {
req.session.gameStarted = true;
req.session.serverStocks = [];
setInterval(function() {
req.session.serverStocks.push('new object');
console.log('This works as it should, returns an array full of objects ->');
console.log(req.session.serverStocks);
}, 4000);
}
else {
console.log('After refresh, this is always empty ->');
console.log(req.session.serverStocks);
console.log('Although this returns "true" as it should which means sessions work OK ->');
console.log(req.session.gameStarted);
}
res.render('pages/homepage', { title: 'Hello' });
});
My goal is when a user loads the page for the first time it'll initialize an empty session object for him/her. Then every 4000 seconds the "new object" string will be added to it. The first visit part is working well, but when I refresh the page the session object is always empty. What am I missing? What is the right way to do this?
/// this is the part from app.js that is related to session
var session = require('express-session')({
secret: 'shhh_very_secret',
resave: true,
saveUninitialized: true,
cookie: { secure: false }
});
var sharedsession = require("express-socket.io-session");
// Express
var app = express();
// Config (game and app settings)
var config = require('./config/config.js');
app.config = config;
// Session
app.use(session);
// Socket.io
app.io = socket_io();
app.io.use(sharedsession(session, {
autoSave:true
}));
I was using socket.io but after I removed it from the client side so it shouldn't affect the code (or?).
// EDIT: I think the code inside setInterval function is working with some own scope because it's not really adding anything to my object if I check it outside of the function
Express doesn't support sessions out of the box. Make sure you are using middleware that adds sessions, eg https://github.com/expressjs/session
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.