gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:35:29 25 4
gpt4 key购买 nike

我想从 socket.io middleware 传递一些数据到发出的event .我正在从请求中提供的 header token 中提取一些详细信息,并将提取的数据附加到 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);
});
一切正常,我唯一关心的是这种方法是否万无一失?是否保证 middleware 中附加的数据将始终在 event 中访问,或者是否存在我的附加数据将在事件中被覆盖/丢失的情况?
middleware 传递数据是否正确?到发出的 event ?

最佳答案

像这样的东西应该可以编辑:即使使用 typescript 也可以正常工作


/* 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();
});


/* 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);
})
});

关于javascript - 将数据从 socket.io 中间件传递到事件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66053815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com