Django 只能处理 ASGI/HTTP 个连接,不能处理 websocket

Django can only handle ASGI/HTTP connections, not websocket

您好,我遇到了一个错误。

来这里之前,我尝试了很多不同的方式,并查看了之前在这里打开的主题。但是无论我做什么,它总是给我错误。

我尝试了 daphne 和 uvicorn,但结果是一样的,它在本地环境中打开,但在服务器上不起作用,并出现此错误:

Django 只能处理 ASGI / HTTP 连接,不能处理 websocket

我的代码:

Js代码:

<script>

function connectSocket() {
var ws = new WebSocket('ws://' + window.location.host + '/ws/notification/{{request.user.id}}/')

ws.onopen = function(event){
console.log('opened', event);
}

//If there is a long onmessage codes here, I removed the code, no syntax error

ws.onclose = function(e) {
console.error('Chat socket closed unexpectedly; reconnecting');
setTimeout(connectSocket, 1000);
};

ws.onerror = function(event){
console.log('error', event);
}

// window.setInterval(function(){
// loadNotifications();
// }, 1000);
}
connectSocket();
</script>

Settings.py
[/JSR]
[CODE]
CHANNEL_LAYERS = {
"default": {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [("redis", 6379)],
},
},
}



ASGI_APPLICATION = "thesite.routing.application"

asgi

import os
import django
from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'thesite.settings')

django.setup()

application = get_default_application()

Nginx:

server {
listen 80;
server_name **.net www.**.net; #** = site name
root /home/ftpuser/project; 

location /static/ {

alias /home/ftpuser/project/site/static/;
}

location /media/ {
}

location / {

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_pass http://unix:/home/ftpuser/project/thesite.sock;
}


location /ws/ {

proxy_pass http://0.0.0.0:9001;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;


}







}

哦不=(这个错误是语法错误

proxy_set_header Connection "upgrade";

更改为:

proxy_set_header Connection “upgrade”;

但是现在我给了404错误

failed: Error during WebSocket handshake: Unexpected response code: 404

我猜原因 无法处理 ASGI_APPLICATION 参数