I have a React frontend app that needs to send a request to my Backend written in Django
My frontend and backend are now on the same domain but different subdomains.
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 = [
'corsheaders.middleware.CorsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'django.middleware.locale.LocaleMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
]
ALLOWED_HOSTS = ["*"]
CORS_ALLOW_ALL_ORIGINS = True
views.py (where I create the api)
@csrf_exempt
@api_view(["GET"])
@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://subdomain.mydomain/get/id", {
method: 'GET',
headers: {
'Authorization': `Token mytoken`,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
// Other possible headers
}
}).then((res) => console.log(res));
UPDATE
When I make the call without giving the headers, it works, problem is I need to send my token to my backend for validation