Sunday, 4 June 2017

Node.js - accessing node-session variables inside socket.io event

I'm having problems with accessing a session that is stored in req. Here's the code

const express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
nodeSession = require('node-session'),
session = new nodeSession({secret: 'something'});

server.listen(3000);

app.get('/', (req, res) => {
    session.startSession(req, res, () => {
        var page = req.session.has('login') ? '/index.html' : '/login.html';
        res.sendFile(__dirname + page);
    });
});

app.post('/login', (req, res) => {
    session.startSession(req, res, () => {
         //some code that connects to database and sets session
    });
});

io.sockets.on('connection', (socket) => {
    socket.on('message', (msg) => {
        //get access to session variable and emit it. There's the problem...
    });
});

The problem is I don't know how to access the req.session inside socket event. Any way around this?



via ruler23

No comments:

Post a Comment