Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS not working in Django but settings seem correct

Tags:

I am trying to make a POST call to Django from a React Native Web front end on different subdomains.

I thought I had configured CORS correctly, but that does not seem to be the case.

Here's what my Django settings.py looks like:

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = ['*']

CORS_ALLOWED_ORIGINS = ['https://api.example.com', 'https://example.com', 'https://www.example.com' ]

CSRF_TRUSTED_ORIGINS = [
    'https://api.example.com', 'https://example.com', 'https://www.example.com'
]

ALLOWED_HOSTS = ["0.0.0.0", "api.example.com", "example.com"]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
]

INSTALLED_APPS = [
     ...
    'corsheaders',
     ...
]

What exactly am I doing wrong here? The error I'm getting is this:

Access to XMLHttpRequest at 'https://api.example.com/api/v1/pagescreate/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And this is my Django view:

class PageCreateView(generics.CreateAPIView):
    queryset = Page.objects.all()
    serializer_class = PageSerializer

What could be causing this? Am I missing some setting in React? I'm using axios to make the calls, with the only header being "Content-Type": "application/json"

EDIT: Could this be due to some nginx rule on my server? Or maybe my Kubernetes configuration? I am using Docker to set it up the container and can easily link the Dockerfile, or any information from my Kubernetes setup

like image 822
Steven Matthews Avatar asked Apr 30 '21 03:04

Steven Matthews


1 Answers

I had this issue before and I suggest to use:

CORS_ORIGIN_ALLOW_ALL = True   

that will allow all origins

with this config ofcourse:

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

INSTALLED_APPS = [
     ...
    'corsheaders',
     ...
]
like image 51
Assem Avatar answered Sep 30 '22 15:09

Assem