0

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

Yorbjörn
  • 356
  • 3
  • 21

2 Answers2

-1

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.

DrayNeur
  • 9
  • 1
  • Hello, thanks for the tip, I just made sure that both of them are on the same domain but I still get the error? they are on a different subdomain tho – Yorbjörn Aug 29 '22 at 11:11
-1

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",]
Iqbal Hussain
  • 1,077
  • 1
  • 4
  • 12
  • Did that but doesn't work at all for some reason – Yorbjörn Aug 29 '22 at 11:11
  • @Yorbjörn, Can you show here your settings.py please. How you managed it for cors-headers. `CORS_ALLOWED_ORIGINS = ["http://localhost:3000"]` Where is your API port? – Iqbal Hussain Aug 29 '22 at 15:39
  • I just updated my question, where I now set ```CORS_ALLOW_ALL_ORIGINS = True``` which should mean that every domain is allowed? I also found out that it simply works when I remove the "headers" part in my request in the frontend. sadly the headers are needed to send my token with my request – Yorbjörn Aug 30 '22 at 12:15
  • @Yorbjörn , Please do that and check again. `CORS_ALLOWED_ORIGINS = [ http://127.0.0.1:3000, #For React Project http://127.0.0.1:8000 #For Django Project ]` – Iqbal Hussain Aug 30 '22 at 15:29