djangoreactjsdjango-rest-frameworkreact-router

How can I setup Django and React on the same port and handle routing?


The Problem

Hi! I’m trying to setup my Django-React app but I can’t manage to get both to run in the same port (Django Rest API is in port 8000 and react in 3000) using the react router links and routes.

I am using django, djangorestframework, react, react router and react router dom. Please help 🤓😅

Django's API works perfectly for get and post requests and they load perfectly with ListCreateAPIViews

Here are some pictures of my files. Let me know if you need any more info.

The Pictures

Project Structure

Project Structure

models.py

enter image description here

serializers.py

enter image description here

api/urls.py

enter image description here

urls.py

enter image description here

settings.py

enter image description here


Solution

  • A port is a specific networking endpoint that is bound to an application instance running on the server. For example, typically if I want to connect to my server via ssh I will need to connect via port 22. Since SSH is running on port 22, nothing else can run there because how would the computer know if the traffic coming into port 22 was for ssh or the other application listening there? That is why there are thousands of ports that you can use and why django and react run on different ports if you are running them at the same time. If you're interested I'd read up a bit on ports and some other basic networking topics.

    Now I think what you're asking is: I want to run react and django together and I want them to be able to communicate. For this running in different ports is fine, for development just point the react app to communicate with django over the specified port and the same for django. When you actually go to launch an app in production, you will run the program on the server and bind it to a port then your clients will hit the api using that specified port. Because they aren't running on the same machine in production, there will be no collisions so this is fine. Sometimes you have the situation where lots of things try to connect at the same time and if something is already connected on that port, the connection will be refused. That is why webserver can be configured to listen on a specific port and forward traffic to others so many users can be serviced simultaneously.