2

I have a function that opens a connection to a server and logs the response. The function is using XMLHttpRequest, I want the very same function using Web Socket instead. Is this possible? Here is my code:

function httpGetAsync(theUrl, callback){
    let token = "ABC123";

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
        }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.setRequestHeader('Authorization', 'Bearer ' + token);
    xmlHttp.send(null);
}

What I have tried so far:

function wsTest(url){
    if ("WebSocket" in window) {
        var ws = new WebSocket(url);

        ws.onopen = function() {
          ws.send('Authorization', 'Bearer ' + token);
        };

        ws.onmessage = function (evt) { 
          var received_msg = evt.data;
          console.log("Message is received...");
          console.log(received_msg);
        };

        ws.onclose = function() { 
          console.log("Connection is closed..."); 
        };
    }
}

I can't figure out how to properly add the xmlHttp.setRequestHeader('Authorization', 'Bearer ' + token); part to the Web Socket.

Phrosen
  • 183
  • 2
  • 15
  • https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api – epascarello Apr 25 '18 at 13:52
  • @epascarello I tried that, I couldn't make it work. Which is why I am asking for help. – Phrosen Apr 25 '18 at 13:53
  • 1
    This is the problem with websockets.. they can apparently be far superior in certain circumstances but it's practically impossible to learn how to actually use them. Everyone seems to have opinions on websockets but when you ask a specific coding question everyone is silent. – Normajean May 21 '21 at 12:18

0 Answers0