Django CORS 问题:不允许访问控制允许来源

时间:2021-06-24 07:14:45

标签: python django django-rest-framework cors django-cors-headers

我收到以下错误:

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.

我已经尝试添加 django-cors-headers 中间件和 CORS_ALLOW_ALL_ORIGINS = True,我也制作了 ALLOWED_HOSTS = ['*'] 但仍然遇到相同的 CORS 错误。 我在使用 NestJS 时遇到了同样的错误,但在添加 app.enableCors(); 后它得到了解决。

这是我的 settings.py 文件:

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

2 个答案:

答案 0 :(得分:0)

您还需要 CORS_ALLOW_CREDENTIALS,因为 django 需要 CSRF cookie 来验证请求。

<块引用>

如果为 True,将允许 cookie 包含在跨站点 HTTP 请求中。默认为假。注意:在 Django 2.1 中添加了 SESSION_COOKIE_SAMESITE 设置,默认设置为“Lax”,这将防止 Django 的会话 cookie 被跨域发送。将其更改为 None 以绕过此安全限制。

答案 1 :(得分:-1)

我发现了我的错误。我没有正确理解错误信息 我专注于错误消息的前半部分,但后半部分显然指向不同的问题 错误的重要 0art 是:

“预检响应中的 Access-Control-Allow-Headers 不允许请求头字段 access-control-allow-origin”

在我拼命解决这个问题的过程中,我的第一反应是在我的 http 请求中提供一个 cors 标头,就像这样

标题:{ 'Access-Control-Allow-Origin': '*', }

这是错误的,因为我正在发送自定义标头,并且消息非常清楚地说明“这是不允许的”!

只需从我的请求中删除这一行即可解决问题。