Akshat Tamrakar
Akshat Tamrakar

Reputation: 2339

Django CORS issue: access-control-allow-origin is not allowed

I'm getting following error:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/' from origin 'http://localhost:62570' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I have tried adding django-cors-headers middleware and CORS_ALLOW_ALL_ORIGINS = True and I have also made ALLOWED_HOSTS = ['*'] but still getting same CORS error. I had the same error with NestJS but after adding app.enableCors(); it got resolved.

Here is my settings.py file:

from pathlib import Path

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    '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',
]
ROOT_URLCONF = 'basic_app.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'basic_app.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'

# CORS
CORS_ALLOW_ALL_ORIGINS = True

# CORS_ALLOWED_ORIGINS = [
#     "http://localhost:62570",
#     "https://example.com",
#     "https://sub.example.com",
#     "http://localhost:8080",
#     "http://127.0.0.1:9000"
# ]

Upvotes: 7

Views: 6841

Answers (3)

wroscoe
wroscoe

Reputation: 2014

I had this same issue when debugging a vue.js app on Brave and found that in addition to the instructions provided here I needed to add

CORS_ALLOW_HEADERS = "*"

or

CORS_ALLOW_HEADERS = "access-control-allow-origin"

above the INSTALLED_APPS section of your settings.py

This way the response to the preflight OPTIONS request will include a header Access-Control-Allow-Headers that includes the access-control-allow-origin

Upvotes: 2

Akshat Tamrakar
Akshat Tamrakar

Reputation: 2339

I found my bug. I didn't understood the error message properly I focused on first half of error message but the later half was clearly pointing to different issue The important 0art of error was :

"Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response"

In my desperate attempts to solve the issue, my first reaction was to provide a cors header in my http request like this

headers: { 'Access-Control-Allow-Origin': '*', }

Which was wrong as it I was sending custom header and as the message states quite clearly "this was not allowed"!

Just removing this one line from my request solved the issue.

Upvotes: 1

Sadan A.
Sadan A.

Reputation: 1107

You also need CORS_ALLOW_CREDENTIALS as django requires CSRF cookies to validate the requests.

If True, cookies will be allowed to be included in cross-site HTTP requests. Defaults to False. Note: in Django 2.1 the SESSION_COOKIE_SAMESITE setting was added, set to 'Lax' by default, which will prevent Django’s session cookie being sent cross-domain. Change it to None to bypass this security restriction.

Upvotes: 0

Related Questions