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.
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.
CodePudding user response:
- install
django-cors-headers
:
pip install django-cors-headers
- Add
corsheaders
toINSTALLED_APPS
insettings.py
:
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
- Add
CorsMiddleware
to your middlewares insettings.py
:
MIDDLEWARE = [
...,
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
...,
]
- 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.