Node.js - express session

I am using node.js and expressing socket.io. I am using a session in Express.

How can I read a session and work with it in socket.io - in the part with communication?

store.userid undefined.

var express = require('express') , stylus = require('stylus') , nib = require('nib') , sio = require('socket.io') , ejs = require('ejs'); store = new express.session.MemoryStore; app.configure(function () { app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: 'secret', store: store })) app.use(stylus.middleware({ src: __dirname + '/public', compile: compile })) app.use(express.static(__dirname + '/public')); app.set('views', __dirname); app.set('view engine', 'ejs'); //disable layout app.set("view options", {layout: false}); }); app.get('/', function(req, res) { req.session.userid = Math.floor(Math.random()*5000); }); var io = sio.listen(app) , nicknames = {}; io.configure(function () { io.set('transports', ['websocket','flashsocket','xhr-polling']); }); io.sockets.on('connection', function (socket) { socket.emit('hello', { hello: store.userid }); //store.userid is undefined }); 

In the variable store:

store =

 { sessions: { 'DNHIsZqgk53zbK3xg8qescJK.dUbdgfVq0D70UaLTMGTzO4yx5vVJral2zIhVsfFGnBA': '{"lastAccess":1326317111111,"cookie":{"originalMaxAge":14399999,"expires":"2012-01-12T01:28:17.266Z", "httpOnly":true,"path":"/"},"userid":3528}' }, hash: [Function], generate: [Function] } 
+4
source share
1 answer

I could be wrong, but I don't think you can (or should) rely on an http session that will populate when the connection event handler starts. They probably work on different protocols, and the http session depends on the browser cookie (which socket.io can send when it polls xhr, but probably won't if it uses a β€œreal” socket).

I would recommend that your JS client somehow extract the cookie (or at least the session identifier) ​​manually (either by extracting cookies using JS, or if you want to write it to the page somehow ... on your choice). Then, when the client establishes a connection, it can pass this value, and you can use it to associate it with the session. There are some documents on how to make material that lasts the entire session on the github page; do a search for "session" here: https://github.com/learnboost/socket.io

+2
source

Source: https://habr.com/ru/post/1390528/


All Articles