【发布时间】:2020-01-21 10:55:53
【问题描述】:
频道。到目前为止,我已经成功运行了服务器,因为这出现在我的 cmd 提示符中:
System check identified no issues (0 silenced).
January 21, 2020 - 17:43:42
Django version 3.0.2, using settings 'crm.settings'
Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
但是我在控制台中遇到了这个错误:
Failed to load resource: the server responded with a status of 404 (Not Found)websocketbridge.js:1
Uncaught ReferenceError: channels is not defined
at HTMLDocument.<anonymous> ((index):353)
这是我的代码。
在我的设置中:
ALLOWED_HOSTS = ["0.0.0.0","127.0.0.1"]
INSTALLED_APPS = [
'channels',
.....
]
WSGI_APPLICATION = 'crm.wsgi.application'
ASGI_APPLICATION = 'crm.routing.application'
在我的 routers.py 中:
from channels.routing import ProtocolTypeRouter , URLRouter
from django.urls import path
from rnd.consumers import EchoConsumer
application = ProtocolTypeRouter({
"websocket": URLRouter([
path("ws/",EchoConsumer)
])
})
在我的 consumer.py 中:
from channels.consumer import AsyncConsumer
类 EchoConsumer(AsyncConsumer):
async def websocket_connect(self,event):
await self.send({
"type" : "websocket.accept"
})
async def websocket_receive(self,event):
await self.send({
"type" : "websocket.send",
"text" : event["text"]
})
在我的 html 中:
<script src="{% static '/channels/js/websocketbridge.js' %}"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function(){
const webSocketBridge = new channels.WebSocketBridge();
webSocketBridge.connect('/ws/');
webSocketBridge.listen(function(action,stream){
console.log("RESPONSE:",action,stream);
})
document.ws = webSocketBridge;
})
</script>
有人对此有解决方案吗?
【问题讨论】:
标签: javascript html django django-channels