Django CORS configuration not working despite middleware setup

I'm encountering an issue with CORS (Cross-Origin Resource Sharing) configuration in my Django project. Despite configuring CORS settings in my settings.py and adding the CorsMiddleware to the MIDDLEWARE list, I still encounter CORS-related errors when making requests from my frontend application.

Here's a summary of my configuration:

settings.py (CORS and CSRF settings):

# CORS
CORS_URLS_REGEX = r"^/api/.*$"
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = config("CORS_ORIGIN_WHITELIST", cast=Csv(), default=["http://localhost:3000"])
CORS_ALLOWED_ORIGINS = config("CORS_ALLOWED_ORIGINS", cast=Csv(), default=["localhost:3000"])
CORS_ALLOW_ALL_ORIGINS = config("CORS_ALLOW_ALL_ORIGINS", default=True, cast=bool)
CORS_ALLOW_METHODS = (
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
)
CORS_ALLOW_HEADERS = list(default_headers) + ["Set-Cookie"]

# CSRF
CSRF_TRUSTED_ORIGINS = config("CSRF_TRUSTED_ORIGINS", cast=Csv())

CSRF_USE_SESSIONS = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = None
SESSION_COOKIE_SAMESITE = None

settings.py (MIDDLEWARE):

MIDDLEWARE = (
    "django.middleware.security.SecurityMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "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",
)

Despite having these settings in place, when I attempt to make a request from my frontend application (https://example.com) to my Django backend (https://api.example.com/api/v1/), I receive the following error:

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

Failed to load resource: net::ERR_FAILED

Also I get this result from Postman: enter image description here

Django version: 4.2.1 django-cors-headers version: 4.3.1

Back to Top