将数据从socket.io中间件传递到事件的正确方法

sai*_*web 6 javascript node.js dom-events socket.io

我想将一些数据从 socket.io 传递middleware到已发出的event. 我从请求中提供的标头令牌中提取一些详细信息,并将提取的数据附加到对象中,socket如下所示:

/* extracting details from token, before connecting */
io.use((socket, next) => {
    const details = fetchDetails(socket.request.headers.token);
    // appending details to socket object
    socket.details = details;
    next();
});

/* on connection event */
io.on("connection", (socket) => {
    console.log('Client conected');
    // accessing details fetched in the middleware
    console.log(socket.details);
});
Run Code Online (Sandbox Code Playgroud)

一切正常,我唯一关心的是这个方法是否万无一失?是否保证附加在 中的数据middleware将始终可在 中访问event,或者是否会出现我附加的数据在事件中被覆盖/丢失的情况?

这是将数据传递middleware到发出的正确方法吗event

小智 9

像这样的东西应该可以工作编辑:即使使用打字稿它也能正常工作


    /* extracting details from token, before connecting */
    io.use((socket, next) => {
        const details = fetchDetails(socket.request.headers.token);
        // use socket.data to pass additional attachments
        socket.data = details;
        next();
    });

Run Code Online (Sandbox Code Playgroud)

    /* on connection event */
    io.on("connection", (socket) => {
        console.log('Client conected');
        // accessing details fetched in the middleware from socket.data object
        console.log(socket.data);
        
        //If you want to pass another object in emit() from frontend
        socket.on("some_action", (anotherData) => {
          //Here's your data from event
          console.log(anotherData);
          
          //And here's your data from middleware
          console.log(socket.data);
        })
    });

Run Code Online (Sandbox Code Playgroud)