未捕获的 DOMException:构造 'WebSocket' 失败:URL 'ws://127.0.0.1:8000:8001/public_chat/' 无效

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

所以,我正在使用 Python Django Channels 和 JavaScript。我想用 Django 构建一个 Websocket 并用 Javascript 连接到它,但现在我得到了这个错误。所以我知道,127.0.0.1:8000:8001/public_chat/ 不能是有效的 URL :)

这是我的 Javascript 代码:

<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>```

它不是有效的 URL,因为它指定了两个端口。你可以改变你的逻辑来决定 ws_path 像这样:

{% 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}}";

这样您就可以选择要使用的端口。