Express session and express-socket.io-session function do not work in angular2 / typecript environment

So, I have a script.js that installs the server this way:

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 environment of typescript / angular2, using the following seed https://github.com/NathanWalker/angular2-seed-advanced I make HTTP requests in several services / components using the Http class.

However, when I try to request the server again for something, I try to register a user session, nothing is logged ... I really don’t know why this is happening, since not only the session is not for the user but the session is not shared with http at socket level system (as is obvious, if it is not created, it is also not shared).

Does anyone know what might be wrong here? I can provide more information if necessary, but I do not know what is missing ... Thank you very much for your help.

+5
source share
1 answer

You can easily run socket.io with Express. Just by running the socket.ios listening method and passing it the Express Session as middleware ( Assuming you save all your sessions in a FileSystem, not in Redis ). I replicated your code that looks like this:

  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 this helps! Thanks!

+5
source

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


All Articles