未捕获的 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.
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频道和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}}";

表示您选择使用哪个端口。

最新更新