在 websocket 连接中设置 cookie [英] Set cookie inside websocket connection

查看:177
本文介绍了在 websocket 连接中设置 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在握手期间设置 cookie:

I know that I can set cookies during handshake:

const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('headers', headers => {
  headers.push('Set-Cookie: my-cookie=qwerty');
});

如何更改 websocket 连接中的 cookie?例如,我想在一些客户端消息之后设置会话 cookie:

How can I change cookies inside websocket connection? For example, I want to set session cookie after some client message:

ws.on('message', () => {
  // something like ws.setCookie('my-cookie=qwerty');
});

推荐答案

您不能在收到 webSocket 消息时设置 cookie,因为它不是 http 请求.一旦 webSocket 连接建立,它就是一个开放的 TCP 套接字,协议不再是 http,因此没有内置的方式来交换 cookie.

You can't set a cookie upon receipt of a webSocket message because it's not an http request. Once the webSocket connection has been established, it's an open TCP socket and the protocol is no longer http, thus there is no built-in way to exchange cookies.

您可以将您自己的 webSocket 消息发送回客户端,告诉它设置 cookie,然后在客户端中侦听该消息,当它收到该消息时,它可以在浏览器中设置 cookie.

You can send your own webSocket message back to the client that tells it to set a cookie and then be listening for that message in the client and when it gets that message, it can set the cookie in the browser.

这篇关于在 websocket 连接中设置 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆