首页 > 解决方案 > 如何在javascript中创建websocket时发送自定义标头?

问题描述

所以我在 Python 上创建了一个 websocket 连接的以下代码:

channels_dict = {}
channels_dict['Authorization'] = 'true'
for channel in channels: #adds some extra headers with info
    channels_dict["Channel" + str(channel)] = '1'

ws = websocket.WebSocketApp("ws://localhost:8888/ws",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close,
                              header = channels_dict)

而且我可以轻松添加额外的标头,以便稍后在连接时在服务器中访问。有没有办法我可以在 Javascript 中做同样的事情?我没有找到太多关于在 websocket 创建中设置自定义标头的信息。我在 JS 中有以下代码:

var webSocket;

function openWebsocket() {
  webSocket = new WebSocket("ws://localhost:8888/ws")
}

我听说在 url 中添加查询参数,这是在 javascript 中向 websocket 连接添加额外标头/信息的唯一方法吗?

标签: javascriptpythonwebsocket

解决方案


尝试这个:

 const webSocket = new WebSocket ("ws://localhost:8888/ws"  + "?param1=" + param1); // here you can add other params
 webSocket.on("open", function open(e) {
   console.log("*** websocket opened");
 });

推荐阅读