Home > OS >  ReactJS with graphql CORS Issue with django backend
ReactJS with graphql CORS Issue with django backend

Time:02-18

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

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

CodePudding user response:

  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.

  • Related