So I'm using middleware to combine the express.js and socket.io sessions (see [this question]). I have implemented it before in a previous version of my code, but I'm struggling now.
login.js
if (bool) {
//create session, return success status
req.session.loggedIn = true;
console.log("Setting login", req.session.loggedIn); //logs true
req.session.user = user[0].id;
req.session.player = new Player(user[0].id, user[0].username);
response.msg = "You have logged in!";
response.flag = false;
console.log(req.sessionID); //logs session id
}
Now if we go to my server, I have it setup with:
const sessionMiddleware = session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {secure:false}
});
//create the server
const server = app.listen(8080, () => {
const port = server.address().port;
console.log(`SourceUndead has risen from the grave on port ${port}`);
});
//attach socket to process
const io = socket.listen(server);
//APPLY THAT SESSION BRAH
io.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
app.use(sessionMiddleware);
Now, when I log in, it should set my req.session variables, and they do log inside login.js, but the session isn't being saved because if I reload the page, it should redirect you to the index page (done by react polling the API). I know that in post routes, the session is only saved if you define req.session.save()
if you don't use res.send()
or a variation. I have tried both.
My server output:
Socket connection NeqQpiNB1BdskTUS7Wd9L19RXu-r20u8
Is logged in undefined
Setting login true
TcC0OVpZuBVFqxEL1bgW9x9zxtXwcGb6
Socket connection Q3S8mSfPWDiAlo54QloyGBGGWHV8hchD
Is logged in undefined
How do I get my session variables to persist on my server?
via Sterling Archer
No comments:
Post a Comment