Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS with graphql CORS Issue with django backend

I have running django backend on http://127.0.0.1:8000 and I want to request it with reactjs frontend.

As you can see below, I can see the successful response in the Insomnia app.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But, When I want a request with reactjs frontend, I get a CORS ERROR.

I check the request in the inspect networks and I saw a similar request payload with insomnia.

enter image description here

>Solution :

  1. install django-cors-headers:
    pip install django-cors-headers
  2. Add corsheaders to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]
  1. Add CorsMiddleware to your middlewares in settings.py:
MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]
  1. Now you can set your allowed origins in settings.py like this:
CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

More info in this link.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading