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.

3
  • @epascarello I tried that, I couldn't make it work. Which is why I am asking for help.
    – Phrosen
    Apr 25, 2018 at 13:53
  • 2
    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, 2021 at 12:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.