I have a React frontend app that needs to send a request to my Backend written in Django
But I'm getting some CORS problems, more specificly, CORS header ‘Access-Control-Allow-Origin is missing.
I found a lot of questions on stackoverflow on how you need to install django-cors-headers but it simply doesn't work for me.
my current backend configuration:
settings.py
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
]
ALLOWED_HOSTS = ["*"]
CORS_ALLOWED_ORIGINS = ["http://localhost:3000"]
CSRF_TRUSTED_ORIGINS = ["http://localhost:3000"]
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
views.py (where I create the api)
@csrf_exempt
@api_view(["POST"])
@permission_classes([AllowAny])
@xframe_options_exempt
def create_user_and_ci(request):
try:
# code to execute
return Response({"status": "Succes"}, status.HTTP_200_OK)
except:
return Response({"status": "Error"}, status.HTTP_500_INTERNAL_SERVER_ERROR)
And then on my frontend i execute this:
fetch(`https://myexampledomain.com/ci/get/${est}`, {
headers: {
Authorization: `Token ${localStorage.getItem("token")}`,
'Content-Type': 'application/json'
},
}).then((res) => console.log(res))
CodePudding user response:
Foremost, this CORS error is due to the fact that your frontend is not on the same domain as your Django API/Backend, so all the Django responses need to contain the CORS related headers here.
I found this post about adding a custom HTTP header with a middleware in Django, this might help you here.
CodePudding user response:
Install this package:
pip install django-cors-headers
INSTALLED_APPS = [
...,
"corsheaders",
...,
]
CORS_ALLOWED_ORIGINS = [
http://127.0.0.1:3000, #For React Project
http://127.0.0.1:8000 #For Django Project
]
In MiddleWare add this in the list
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",]