Django Channels环境下WebSocket无法通过Postman连接问题求助
Django Channels WebSocket仅网页可连接,Postman等工具无法连接的问题
问题描述
在Mac本地运行Django项目,使用Channels实现WebSocket连接:
- 通过项目内的
.html页面可正常连接WebSocket并收发消息 - 相同URL无法在Postman或websocketking.com等外部工具中建立连接
- 部署到正式服务器后问题依旧,仅网页能成功建立连接
相关代码与配置
网页连接代码(myTemplate.html)
const ws = new WebSocket( 'ws://' + window.location.host +'/ws/test/?token=' +'**mytoken**' );
ASGI配置(asgi.py)
import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spacetime.settings.dev') django.setup() from channels.routing import ProtocolTypeRouter,get_default_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import path, re_path from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack from myapp import consumers, routing application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( JWTAuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ) ), })
Django设置(settings.py)
ASGI_APPLICATION = 'spacetime.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', *** ]
日志信息
项目启动日志(VSCode控制台)
Django version 4.1.2, using settings 'spacetime.settings.dev' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
网页连接成功日志
HTTP GET /my/socket/view/ 200 [0.01, 127.0.0.1:60258] WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60260] WebSocket CONNECT /ws/test/ [127.0.0.1:60260]
websocketking.com连接失败日志
WebSocket HANDSHAKING /ws/test/ [127.0.0.1:60759] WebSocket REJECT /ws/test/ [127.0.0.1:60759] WebSocket DISCONNECT /ws/test/ [127.0.0.1:60759]
Postman请求信息
Request URL: http://127.0.0.1:8000/ws/test/?token=mytoken
Request Method: GET
Status Code: 403 Access denied
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 0VRmdvoFhma7lndljwIY6w==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000
Response Headers
确认token有效
websocketking.com提示信息
Could not connect to "ws://127.0.0.1:8000/ws/test/?token=**mytoken**". You may be able to find more information using Inspector/Dev Tools on this page. Connecting to ws://127.0.0.1:8000/ws/test/?token=**mytoken**
提问
请问是什么原因导致无法通过Postman连接?
内容的提问来源于stack exchange,提问作者Ihor Kram
相关产品推荐
相关产品推荐

