Django has the capability to manage ASGI/HTTP connections, but it does not support websockets

Hello, I am encountering an error.

Despite trying various methods and researching previous discussions here, I cannot seem to resolve the issue. Whether I use daphne or uvicorn, the result remains the same - it works locally but fails on the server with the following error:

"Django can only handle ASGI/HTTP connections, not WebSockets."

My Code:

JS Code:

<script>

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

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

// Long onmessage codes omitted for brevity

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;


}







}

Answer №1

Uh oh, I encountered a syntax error

proxy_set_header Connection "upgrade";

Should be changed to:

proxy_set_header Connection “upgrade”;

Now I'm getting a 404 error

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

I believe the issue is related to failing to process the ASGI_APPLICATION parameter

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider: inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2} In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as t ...

Tips for utilizing browser cache in AJAX requests to prevent loading the refreshed JSON file

It may seem like a strange question, but I'm experiencing an issue with an AJAX call to a JSON file. Both the request and response headers do not indicate to not use cache, and in the browser settings, the Disable cache option is not checked. What mor ...

Some browsers are experiencing issues with Javascript functionality

My JavaScript code is functioning perfectly on my development machine in Chrome, Firefox, and Safari. However, when others test it on their browsers, the value update does not work at all. Can anyone suggest how I can replicate this issue locally? Browser ...

Exploring the capabilities of batch updates in Firestore with the latest web version-9

I am facing issues when trying to update certain values in my firestore collection within my nuxt project. const batch = writeBatch(firestore); const data = query(collection(firestore, `notifications`, `${uid}/news`)); const querySnapshot = await ...

Discover the dimensions of the viewport using jQuery

I am currently attempting to use jQuery to determine the size of the viewport, but I am not achieving the desired results. Here is my CSS code: .site { max-width: 960px; } @media only screen and (min-width : 760px) and (max-width : 1040px) /* table ...

jQuery plugin modifies keypress events

I have integrated the Jquery ImgAreaSelector plugin into my website. Within my site, I have implemented several keypress triggers using jquery. For example: $(document).bind('keypress', 'S', function(){ alert("You have pressed S key ...

What is the process for executing `Model.objects.values()` using a command-line parameter?

Currently in my Django project, I am working on creating a custom manage.py command named some_command. Below is the code I have implemented so far in management/commands/some_command.py. class Command(BaseCommand): def add_arguments(self, parser): ...

Display script based on inner width - avoiding the use of "potentially harmful request.form"

What I'm Seeking: In order to display affiliate ads on my responsive website, I need to load different javascripts based on the innerwidth property using jQuery. However, attempting to load these scripts in hidden fields and dynamically swapping them ...

Is your SignalR chat struggling to establish a connection with the Hub?

I'm having trouble setting up a SignalR chatroom in asp.net, as I keep encountering the error message "Uncaught TypeError: Cannot read property 'chatHub' of undefined" and the chat prompt doesn't appear as expected. I followed this tuto ...

Converting dates from JavaScript to Central Daylight Time (CDT) using the new

I have a function below that is used to format a date from an API Response. However, when the date "2021-10-02" is received in the response, the new Date() function converts it to Mon Oct 01 2021 19:00:00 GMT-0500 (Central Daylight Time), which is one da ...

Tips for customizing stepper color using hooks in Material UI

Looking for help to change the color of a stepper from 'primary' to 'success' using React hooks. The stepper component does not have a built-in color method like an icon, so I'm struggling to find a solution. Any advice would be gr ...

ng-src unable to bind the data

Utilizing ng-repeat to dynamically fetch my URL and using ng-src to connect that URL through AngularJS. Here is the code: <div class="x_panel" ng-repeat="data in allreviewdata|filter:search"> <div class="x_content"> <div ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Should we bundle everything into one script with webpack, considering Npm and Dev dependency or just dependencies?

Imagine a scenario where we use webpack to bundle all our code into a single JS file, which automatically imports dependencies. In this case, is it necessary to include any dependencies in the package.json, or can they all be listed as --save-dev? Let&apo ...

Explore the power of accessing XML data using JavaScript

Currently, I am dealing with an XML file and attempting to extract data from it. The structure of the XML file is as follows: <doc> <str name="name">Rocky</str> <str name="Last_name">balboa</str> <str name="age ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...