Want to become a full-stack developer? Unsure of what you need to know? Need a helpful point in the right direction? This post will explain how to link your frontend to your backend simply and quickly!
More specifically, I will give a quick way to link two very popular web technologies together: Django and React! We will use Cors Headers to make this magic happen. I know when I was introduced to Django, creating a frontend was always a challenging task and got complicated very quickly. React was a tool that I learned later, that simplified things, and connecting it to Django was ultimately my end goal. This is why I am writing an article to show this solution!
Setup
Firstly, you need to have created a Django project with an app called 'backend'. This will be the API for our project. We then need to install Cors Headers so Django allows our React frontend to make requests:
pip install django-cors-headers
We now need to install our frontend. I will use Vite for this example. CD: to the root of the project and type the following commands:
npm create vite@latest frontend-- --template react
cd frontend
npm install
Then we need to add cors-headers to our installed apps in settings.py . Make sure it looks like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# added below
'backend',
'corsheaders',
]
Then, below, add these lines of code to trust our frontend...
CORS_ALLOWED_ORIGINS = [
'http://localhost:5173', # default port of react
]
CSRF_TRUSTED_ORIGINS = CORS_ALLOWED_ORIGINS
... and add this line to the middleware:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # add this line
]
And that is all you need for settings.py!
Usage
Now we have completed these steps, we can use this project by visiting the react app and making API requests to the backend port (default is 8000). An example of making such a request is:
axios.post('/api/{yourApiView}/', {})
And there you go! You can now connect your react app to your Django backend.
Top comments (0)