Search code examples
javascriptdjangodjango-channels

Uncaught DOMException: Failed to construct 'WebSocket': The URL 'ws://127.0.0.1:8000:8001/public_chat/' is invalid


Uncaught DOMException: Failed to construct 'WebSocket': The URL 'ws://127.0.0.1:8000:8001/public_chat/' is invalid.
    at setupPublicChatWebSocket (http://127.0.0.1:8000/:215:28)
    at http://127.0.0.1:8000/:206:2
setupPublicChatWebSocket @ (index):215
(anonymous) @ (index):206

So, I am working with Python Django Channels and JavaScript. I wanted to build a Websocket with Django and connect to it with Javascript, but now I get this error. So I know, 127.0.0.1:8000:8001/public_chat/ can't be a valid URL :)

Here is my Javascript code:

<script type="text/javascript">
    
    setupPublicChatWebSocket()

    function setupPublicChatWebSocket(){
        // Correctly decide between ws:// and wss://
        var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
        console.log(ws_scheme)
        {% if debug_mode %}
            var ws_path = ws_scheme + '://' + window.location.host + "/public_chat/{{room_id}}"; // development
        {% else %}
            var ws_path = ws_scheme + '://' + window.location.host + ":8001/public_chat/{{room_id}}"; // production
        {% endif %}
        var public_chat_socket = new WebSocket(ws_path);

        // Handle incoming messages
        public_chat_socket.onmessage = function(message) {
            console.log("Got chat websocket message " + message.data);
        };

        public_chat_socket.addEventListener("open", function(e){
            console.log("Public ChatSocket OPEN")
        })

        public_chat_socket.onclose = function(e) {
            console.error('Public ChatSocket closed.');
        };

        public_chat_socket.onOpen = function(e){
            console.log("Public ChatSocket onOpen", e)
        }

        public_chat_socket.onerror = function(e){
            console.log('Public ChatSocket error', e)
        }

        if (public_chat_socket.readyState == WebSocket.OPEN) {
            console.log("Public ChatSocket OPEN")
        } else if (public_chat_socket.readyState == WebSocket.CONNECTING){
            console.log("Public ChatSocket connecting..")
        }
    }
</script>```


Solution

  • it's not a valid URL because it specifies two ports. you could change your logic to decide ws_path to something like:

    {% if debug_mode %}
        var ws_port = 8000;
    {% else %}
        var ws_port = 8001;
    {% endif %}
    
    var ws_path = ws_scheme + '://' + window.location.hostname + ":" + ws_port + "/public_chat/{{room_id}}";
    

    that way you are choosing between which port you want to use.