任务:
我正在使用 NestJS 并尝试查找有关如何将 socket.id 设置为每个已连接到服务器的客户端的 cookie 的信息。
简化的代码片段:
我在文档中找到了这个代码示例:
const io = new Server(httpServer, {
cookie: true
});
// is similar to
const io = new Server(httpServer, {
cookie: {
name: "io",
path: "/",
httpOnly: true,
sameSite: "lax"
}
});
所以,由于我不使用 Express.js(和原生 Node.js),而是使用 Nest.js,所以我尝试将上述代码调整如下:
// event.gateway.ts file
@WebSocketGateway({
namespace: "api/chat",
cors: {
origin: "*",
},
})
export class EventGateway
implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit
{
@WebSocketServer()
server: Namespace<IClientToServerEvents, IServerToClientEvents>;
afterInit(server: Namespace) {
console.log("server: ", server);
server.server.engine.opts.cookie = {
name: "io",
path: "/",
httpOnly: true,
sameSite: "lax",
};
}
// other code...
}
检查代码时没有 typescript 错误,创建应用程序后也没有 javascript 错误。 我试图在初始化连接时找到 Set-Cookie 标头。所以,就是这样,但正如你所看到的,它们还没有设置:
可能的解决方法:
附言:
看起来套接字 cookie 与 HTTP cookie 不同。那么,请告诉我,我应该使用哪种方式将socket.id值设置为HTTP cookie?
似乎没有什么常走的路可走。
我发现Websocket cookie与HTTP cookie不同。
因此,处理此任务的最佳方法是:
建立 websocket 连接后,在 websocket “连接”事件中,前端应该简单地发送一个 HTTP 请求,例如 http://localhost3000/api/set-socket-id
,并将 socketId 放在请求正文中。然后,后端会将socketId设置为HttpOnly cookie。这是代码示例:
// frontend
this.socket.on("connect", async () => {
await fetch("http://localhost3000/api/set-socket-id", {
method: "POST",
credentials: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ socketId: this.socket.id }),
});
});
// backend
@Post("set-socket-id")
@UseGuards(AuthGuard)
setSocketId(
@Req() request: Request,
@Res() response: Response,
@Body("socketId") socketId: string
) {
response.cookie("socket_id", socketId, {
path: "/",
httpOnly: true,
sameSite: "lax",
});
response.sendStatus(200);
}