0

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?

Gagan Singh
  • 200
  • 1
  • 13
  • Did you tried [this](https://create-react-app.dev/docs/proxying-api-requests-in-development/)? – Abdul Niyas P M Dec 13 '20 at 11:16
  • Are you definitely using `http://127.0.0.1:3000` and not for example `http://localhost:3000`. Althought they point to the same thing if you are using the later, that is what you must list in `CORS_ALLOWED_ORIGINS` – tim-mccurrach Dec 13 '20 at 12:08
  • @tim-mccurrach i'm using `http://127.0.0.1:3000` – Gagan Singh Dec 13 '20 at 12:57
  • @AbdulNiyasPM I tried proxy and it works too, but it's only good for development. I need to address CORS issue while producing – Gagan Singh Dec 13 '20 at 12:59
  • @GaganSingh Have you also checked django's output to the terminal? If there is an error before the request even reaches the cors middleware you will also get a cors error in the browser console. It's a long shot, but just a thought. – tim-mccurrach Dec 13 '20 at 13:27
  • @tim-mccurrach Console is not showing any error and it's processing the request with 200 code which is expected – Gagan Singh Dec 13 '20 at 13:33
  • I can recommend good tutorial [about Django and React](https://saasitive.com/django-react/boilerplate/). – pplonski Dec 13 '20 at 17:06

1 Answers1

0

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
Amal Thundiyil
  • 307
  • 1
  • 4
  • 9