'How to connect React to Django?

I am using reactJS as the frontend while Django at the backend. When I make a request from react to Django(react is running at http://127.0.0.1:3000 while Django is running at http://127.0.0.1:8000),

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/categories. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Most likely, it's occurring due to CORS issue. So I installed django-cors-headers and make following changes in my settings.py:-

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_cleanup.apps.CleanupConfig',
    'myapp',
    'corsheaders'
]
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
]
CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1:3000"
]

But the error still persists. How can I make it work?



Solution 1:[1]

What version are you using? Try to Replace

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1:3000"
]

to:

CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]

or:

CORS_ORIGIN_ALLOW_ALL = True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amal Thundiyil