Setting up CORS in Django Rest Framework and React JS

The technologies React JS and Django Rest Framework are some of the best frontend and powerful frontend and backend combinations in Web Technology. And in this post, I’m going to show you how you can set up CORS in Django Rest Framework and React JS.

Watch Video

Install Django Rest Framework

Before installing rest_framework install pip install Django and create a Django project using django-admin startproject drf.

Then install the rest_framework.

pip install rest_framework

Django App

Create an app with name users as we’ll be retrieving the list of users.

django-admin startapp users

Create a Viewsets

The viewsets are a convenient way to list and get the details. Here we’ll create a viewset to list users.
In users\viewsets.py

from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from rest_framework.response import Response

class UserViewSet( viewsets.ModelViewSet ):
    queryset = User.objects.all()
    serializer_class = UserSerializer  

In users\serializers.py

from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = [ 'url', 'username', 'email', 'is_staff' ]    

The Serializers convert the python objects to dictionaries which can then be returned as JSON. They also de-serialize and convert incoming requests to python objects.
They basically act like forms for API.

Register Viewsets into RestFramework router

To use the UserViewSet register it in routers.register() method.
In drf_one\urls.py

from django.urls import path, include
from rest_framework import routers

from users import viewsets as users_viewsets

router = routers.DefaultRouter()
router.register( r'users', users_viewsets.UserViewSet )

urlpatterns = [
    path('', include(router.urls)),
]

Next is the run migrate command by typing.

python manage.py migrate

Install Django CORS Headers

To set up CORS use the django-cors-headers package. which is a simple way to integrate CORS in Django.

pip install corsheaders

Configure Django CORS Headers

We need to specify certain values in settings.py related to cors.
In drf_one\settings.py

ALLOWED_HOSTS=[ ]
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000"
]

INSTALLED_APPS = [
    '...',
    'rest_framework',
    'corsheaders',
    '...',
]

MIDDLEWARE = [
    '...',
    'corsheaders.middleware.CorsMiddleware',
]
  • CORS_ALLOW_ALL_ORIGINS: Takes a boolean value and set whether a few or all the origin to be allowed
  • CORS_ALLOWED_ORIGINS: Takes list with the origin to allow accessing the site.

The final step is to run the Django app using the below command.

python manage.py runserver

Create a React Project

Now create a project using the below command.

npx create-react-app my_app

Fetch Data from React App

In src\App.js clear all the unnecessary code and trigger a server-side ajax call.

import React, { useEffect } from 'react'

function App() {
    const url = 'http://127.0.0.1:8000'

    useEffect( () => {
        init()
    }, [] ) 
    
    const init = async() => {
        let full_url = `${url}/users/`

        let result = await fetch( full_url )
        result = await result.json()

        console.log(`result`, result)
    }

    return ( <> </> );
}

export default App;    

Final Takeaways

This tutorial was all about basic CORS integration and setup for React JS and Django Rest Framework.