【问题标题】:Django channels error loading javascript wrapperDjango 频道错误加载 javascript 包装器
【发布时间】: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


    【解决方案1】:

    频道 >= v2 不支持 websocketbridge

    频道 v2 中有一些库试图恢复其中的一些功能。

    (免责声明我是djangochannelsrestframework 包的开发者)

    您也可以通过浏览器 api 直接使用 WS。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多