Search code examples
javascriptwebsocketgorilla

Failed to construct 'WebSocket': The URL '{{.}}' is invalid


gorilla/websocket example

In this example:

https://github.com/gorilla/websocket/blob/e8629af678b7fe13f35dff5e197de93b4148a909/examples/echo/server.go#L79

The WebSocket is created by:

ws = new WebSocket("{{.}}");

The example works fine.

Problem

But, then I want to use the same code in another JS code like:


var ws;
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
    console.log("OPEN SOCKET");
}
ws.onclose = function(evt) {
    console.log("CLOSE SOCKET");
    ws = null;
}
ws.onmessage = function(evt) {
    console.log("RESPONSE SOCKET: RECEIVED");
}
ws.onerror = function(evt) {
    console.log("ERROR: " + evt.data);
}
ws.send(positions);
ws.close();

I'm getting this error:

Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The URL '{{.}}' is invalid. at AddObjectCommand.execute

I changed WebSocket like this:

ws = new WebSocket("ws://127.0.0.1:8080/echo");

But I'm still getting an error:

WebSocket connection to 'ws://127.0.0.1:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 403

I cannot figure out what I'm doing wrong. What did I miss?

Fix 403

The 403 error got resolved by this suggestion:

https://github.com/gorilla/websocket/issues/367#issuecomment-375971418

By adding:

upgrader.CheckOrigin = func(r *http.Request) bool { return true }

Before:

c, err := upgrader.Upgrade(w, r, nil)

It's not safe to trust all origins, of course. Just a temporary fix.

Yet another error

But another error is thrown:

Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.


Solution

  • The error of:

    Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

    Got resolved by sending data through WebSocket, by its .onopen callback:

    var positions = ...
    
    var ws;
    ws = new WebSocket("ws://127.0.0.1:8080/echo");
    ws.onopen = function(evt) {
        console.log("OPEN SOCKET");
        console.log("SEND: START");
        ws.send(positions);
        ws.close();
    }