Search code examples
reactjsdjangowebsocketdjango-channels

React Django WebSocket connection challenge


The challenge I am facing is in trying to connect my Django backend with React frontend app. The error that I am getting is:

WebSocket connection to 'ws://localhost:8000/ws/week/' failed: _callee$ @ Week.jsx:77

Here is the Week.jsx code:

export default function Week(props) {
  const [scoops, setScoops] = useState([]);
  const ws = useRef(null);

  useEffect(async () => {
    ws.current = new WebSocket("ws://" + window.location.host + "/ws/week/");
    ws.current.onopen = () => console.log("ws opened");
    const res = await fetch("/api/scoops/week/");
    const data = await res.json();
    setScoops(data);
  }, []);

  const rows = [];

  for (let i = 0; i < scoops.length; i++) {
    rows.push(createData(i, scoops[i]?.rank, scoops[i]?.title, scoops[i]?.url));
  }

  return <Base rows={rows} duration="Week" />;
}

Here is the server terminal log:

System check identified no issues (0 silenced).
December 08, 2021 - 10:59:59
Django version 3.2.8, using settings 'app.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET /week/ 200 [0.02, 127.0.0.1:62685]
HTTP GET /api/scoops/week/ 200 [0.14, 127.0.0.1:62685]
WebSocket HANDSHAKING /ws/week/ [127.0.0.1:62695]
WebSocket DISCONNECT /ws/week/ [127.0.0.1:62695]

Any help would be truly appreciated.

Thank you!


Solution

  • The error was a result of my server code not accepting the connection from the frontend. Adding the following code to consumers.py fixed the issue:

    class ChatConsumer(WebsocketConsumer):
        def connect(self):
            self.accept()
    

    Also made changes to routing.py which looks like this now:

    from django.urls import re_path
    
    from . import consumers
    
    websocket_urlpatterns = [
        re_path(r"ws/week/", consumers.ChatConsumer.as_asgi()),
    ]