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

1
  • Did you install this package? pip install django-cors-headers Commented Aug 26, 2022 at 13:42

2 Answers 2

-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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
-2

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",]

4 Comments

Did that but doesn't work at all for some reason
@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?
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 , 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 ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.