Websocket Socket.io 中的快速会话 req.session?

Express-session req.session in Websocket Socket.io?

我尝试在 express 和 socket.io 之间交换会话 -

当我连接到 Websocket 时,我可以在会话中设置 userData 并在另一个 Websocket 事件中再次获取它!

Server.ts

const session =  require("express-session");
const sessionData = {
    name: COOKIE_NAME,
    secret:COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    store: store
}
const expressSession = expressSession(sessionData);

const socketSession = require("express-socket.io-session");
const sharedsession = socketSession(expressSession, {
    autoSave:true
})

 const io = new Server(httpsServer,{
            cors: {
              origin: "https://localhost:3000",
              methods: ["GET", "POST"]
            }
          })
  io.use(sharedsession);
        io.on("connection", (socket: Socket) => {
            socket.on("message",userdata=>{
                var data = socket.handshake || socket.request;
                (data as any).session.userdata = userdata;
                (data as any).session.save();
                console.log("From Session:",(data as any).session.userdata)
            })
            socket.on("getUser",()=>{
                var data = socket.handshake || socket.request;
                console.log("Got it: ",(data as any).session.userdata)// good!
            })
});

但是现在...当我在这样的快速路由中设置会话时:

app.get('/login', function (req, res) {
    req.session.user =  {_id: '', firstname:'Hide', lastname:'myPain',email:'Harold@hiden.com', hasPain: false, };
    res.send('You are now logged in! => isLoggedIn:' + JSON.stringify(req.session.user));
});

现在我想在我的 Websocket 事件中访问这个 req.session.user:

    socket.on("getUser",()=>{
        var data = socket.handshake || socket.request;
        console.log("Got it: ",(data as any).session.user)  // undefined!
    })

我在 req.session.user 的快速路由中设置的 session.user 未定义.. 为什么?它是要像这样工作,还是只是为了在 Websocket 事件之间进行交换?

或者我只需要触发

            (data as any).session.user= newUserDataFromExpressReq;
            (data as any).session.save();

当用户调用我的 express 端点进行登录时在我的 socketio 上?所以它不是真正的自动交换?

好的,所需要的只是向客户端添加 "withCredentials" 选项。当您的客户端和服务器 运行 在不同的 servers/ports.

上时,这是必需的
// client-side
const io = require("socket.io-client");
const socket = io("https://api.example.com", {
  withCredentials: true,
  extraHeaders: {
    "my-custom-header": "abcd"
  }
});