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.