5

I have a script.js setting the server up that goes like this:

var io_session = require("express-socket.io-session");

var e_session = require("express-session")({
    secret: "a-secret",
    resave: true,
    saveUninitialized: true
});

(...)

//this block is the last "io.use" before the socket logic (io.on("connection"))    
io.use(io_session(e_session,{
    autoSave: true
}));

In my typescript / angular2 frontend enviroment using the following seed https://github.com/NathanWalker/angular2-seed-advanced I perform http requests in several services / components using the Http class.

However, when I try to request the server again for something I try to log the user session, nothing is logged... I don't really know why this is happening as not only the session for the user is not being kept but also the session is not being shared from the http to the socket layer system (as obviously, if it isn't created it isn't also being shared).

Does anyone know what might be wrong here? I can provide more info if needed but I don't really know what is missing.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Fane
  • 1,785
  • 4
  • 23
  • 53
  • Hi, please update your question with more details, like a more complete code lines and overview around the problem. Try a jsfiddle if it suits you better... – bosco Dec 08 '16 at 11:28
  • @dscastro That is hard because the context of the angular2 seed is complex already... – Fane Dec 09 '16 at 17:50
  • This solved it for me: https://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x – James Trickey Jul 20 '17 at 10:06

1 Answers1

5

You can have socket.io run with Express easily. By simply invoking socket.io’s listen method and passing it the Express Session as a Middleware(Assuming you are storing all your sessions in FileSystem and not in Redis). I have made a replication of your Code which goes as follows:

    var e_session = require("express-session"); 
    var io_session = require("socket.io")(server); 
    //Storing sessions in file system
    var sessionFileStore = require('session-file-store')(Session);

    //Express-Sessions as middleware
    var e_sessionMiddleware = e_session({
        store: new sessionFileStore({ path: './project-x/sessions' }),
        secret: 'pass',     resave: true,
        saveUninitialized: true 
    });
    //Use of Express-Session as Middleware    
    io_session.use(function(socket, next) {
       e_sessionMiddleware(socket.handshake, {}, next); 
    });

    //Socket Io session and express sessions are now same 
    io_session.on("connection", function(socket) {
       socket.emit(socket.handshake.session);
    });

Hope it helps! Thank You!

Rohit Rai
  • 377
  • 4
  • 21
  • Didnt u find The answer useful? – Rohit Rai Dec 12 '16 at 11:09
  • It still does not work. I think the problem is in the HTTP object of angular, not in the server. When I refresh the page on angular the socket does not persist... – Fane Dec 28 '16 at 17:46