You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django应用中WebSocket连接失败问题求助(附错误信息及代码)

Django WebSocket连接失败问题排查

错误信息

WebSocket connection to 'ws://127.0.0.1:8000/chat/' failed:

我的JavaScript代码

let loc = window.location
let wsStart = 'ws://'

if(loc.protocol === 'https:') {
    wsStart = 'wss://'
}

let endpoint = wsStart + window.location.host + loc.pathname;

var socket = new WebSocket(endpoint)

socket.onopen = async function(e){
     console.log('open', e)
}
socket.onmessage = async function(e){
     console.log('message', e)
}

routing.py代码

websocket_urlpatterns = [
   path('ws/chat/', consumers.ChatConsumer.as_asgi()),
]

问题分析与解决

  • 核心问题:路径不匹配
    前端请求的WebSocket路径是/chat/,但后端路由配置的是ws/chat/,两者路径不一致导致连接失败。

  • 修正前端Endpoint
    两种方法可选:
    方法一:给当前路径添加ws前缀

    let endpoint = wsStart + window.location.host + '/ws' + loc.pathname;
    

    方法二:直接指定完整的WebSocket路由路径

    let endpoint = wsStart + window.location.host + '/ws/chat/';
    
  • 检查ASGI配置
    确保项目根目录的asgi.py正确集成WebSocket路由,示例配置如下:

    import os
    from django.core.asgi import get_asgi_application
    from channels.routing import ProtocolTypeRouter, URLRouter
    from channels.auth import AuthMiddlewareStack
    import your_app.routing  # 替换为你的应用路由模块
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
    
    application = ProtocolTypeRouter({
        "http": get_asgi_application(),
        "websocket": AuthMiddlewareStack(
            URLRouter(
                your_app.routing.websocket_urlpatterns
            )
        ),
    })
    
  • 使用ASGI服务器启动项目
    Django默认开发服务器不支持WebSocket,需要用daphne或uvicorn启动:

    # 安装并使用daphne
    pip install daphne
    daphne your_project.asgi:application
    

    或者用uvicorn:

    pip install uvicorn
    uvicorn your_project.asgi:application --reload
    

内容的提问来源于stack exchange,提问作者Otu William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:00:54