I get this error only in chrome (not in safari and not in firefox) when trying to connect to the server via a websocket:
Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
.
The server accepts the connection but chrome unexpectedly closes it immediately.
This is how I create a websocket connection on the frontend:
const websocket = new WebSocket('ws://127.0.0.1:8000/ws/', ['Token', 'user_secret_token'])
This is how my consumers.py
looks:
class MyConsumer(JsonWebsocketConsumer):
def connect(self):
self.room_group_name = 'example_room'
# Join room group
async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name)
self.accept()
The solution was to add the websocket protocol I was using (Token) as the subprotocol parameter when I call self.accept()
on the server.
So here is how my consumer looks now:
class MyConsumer(JsonWebsocketConsumer):
def connect(self):
self.room_group_name = 'example_room'
# Join room group
async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name)
# incorrect
# self.accept()
# correct
self.accept('Token')