CORS在特定应用程序中不起作用-Django



我有一个名为auth的现有应用程序,它允许新用户在登录后创建帐户或获取auth令牌。这里一切似乎都很好。不存在CORS问题,但当我启动一个名为Blog的新应用程序并试图通过Axios请求访问其视图时,我得到了CORS错误:即使我的CORS策略初始化,也不存在允许访问的原始标头。

以下是我的settings.py:的片段

Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-3mr!aqng!tc!*ko7i!*&y9x8k-*y$@1pc+$g!_^-aol4!vd@tn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'django_rest_passwordreset',
'corsheaders',
'auth_app',
'blog'
]
MIDDLEWARE = [
'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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'backend.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 = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
],
"DEFAULT_AUTHENTICATION_CLASSES": [
'rest_framework.authentication.TokenAuthentication'
],
}
AUTH_PWD_MODULE="django.contrib.auth.password_validation."
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": f"{AUTH_PWD_MODULE}UserAttributeSimilarityValidator",
},
{
"NAME": f"{AUTH_PWD_MODULE}MinimumLengthValidator",
},
{
"NAME": f"{AUTH_PWD_MODULE}CommonPasswordValidator",
},
{
"NAME": f"{AUTH_PWD_MODULE}NumericPasswordValidator",
},
]
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_ROOT =  os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#CORS
CORS_ORIGIN_ALLOW_ALL = True

正如你所看到的,CORS被初始化为它应该是,甚至我的身份验证应用程序也能正常工作。那么,当我试图访问博客应用程序的端点时,为什么会发生这种情况呢?

跟进@jub0bs评论-我同意您遇到的问题可能是由于CORS中间件组件位于已安装中间件列表的底部所致。尝试将这个中间件组件移到中间件列表的顶部,看看这是否解决了问题。

正如django-cors标题GitHub页面上提到的:

CorsMiddleware应该放得尽可能高,尤其是在任何可以生成响应的中间件(如Django的CommonMiddleware或Whitenoise的WhiteNoiseMiddleware(之前。如果不是以前,它将无法将CORS标头添加到这些响应中

相关内容

  • 没有找到相关文章

最新更新