简体   繁体   中英

How to send custom headers in websocket creation in javascript?

So I had the following code on Python that created a websocket connection:

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)

And I could easily add extra headers that I could access later in the server upon connection. Is there a way I could do the same in Javascript? I haven't found much information about setting custom headers in websocket creation. I have the following code in JS:

var webSocket;

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

I've heard of adding query parameters in the url, is that the only way of adding extra headers/information to a websocket connection in javascript?

Try this:

 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");
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM