I am currently building an application with django channels.
I have a websocket connected to a server. Looking at my terminal, it seems like the websocket is successfully connected to the server.
HTTP GET / 200 [0.01, 127.0.0.1:62087] HTTP GET /static/video/js/websocket.js 200 [0.00, 127.0.0.1:62087] WebSocket HANDSHAKING /ws/video [127.0.0.1:62089] WebSocket CONNECT /ws/video [127.0.0.1:62089]
However, the websocket does not receive the message sent from the server.
Here are my codes:
consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class VideoConsumer(WebsocketConsumer):
def connect(self):
self.accept()
self.send(json.dumps({'message': 'you are connected!'}))
websocket.js
const address = 'ws://' + window.location.host + '/ws/video'
const websocket = new WebSocket(address)
const btn = document.getElementById('myButton')
websocket.onopen = (event) => {
console.log('websocket connected!!!')
}
websocket.onmessage = (event) => {
console.log(event.data)
}
I would like to receive the message "you are connected!" on my browser's console. I looked into the official django channels document and google searched for a solution but I failed to solve my issue. What am I missing here?
The issue had nothing to do with the codes above.
I have solved the issue by editing my asgi.py under the project folder.
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from channels.auth import AuthMiddlewareStack
import video.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'VideoChat.settings')
application = ProtocolTypeRouter(
{
'http': get_asgi_application(),
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter(video.routing.websocket_urlpatterns))
)
}
)
As you can see, I have wrapped the AuthMiddlewareStack(URLRouter(video.routing.websocket_urlpatterns))
with AllowedHostsOriginValidator
. After I removed the AllowedHostsOriginValidator
like 'websocket': AuthMiddlewareStack(URLRouter(video.routing.websocket_urlpatterns))
, the issue was solved perfectly.
p.s: I have noticed that the websocket can still be connected with the previous setting. It just neither send a message nor receive a message from the server.