javascript - 如何在 django Rest 框架中使用 CORS?

标签 javascript python django django-rest-framework fetch

我已将 django-cors-headers 用于 CORS,但无法让 CORS 以正确的方式工作。

就像从客户端一样,我可以从不在允许主机中的任何主机运行代码,但请求仍然完成,没有任何 CORS 错误。

谁能告诉我,我怎样才能只允许白名单主机?

我的settings.py

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 = os.environ["SECRET_KEY"]

# SECURITY WARNING: don't run with debug turned on in production!

SECURITY_TRUE = True
SECURITY_FALSE = False

DEBUG = False

CSRF_COOKIE_SECURE = True

SESSION_COOKIE_SECURE = True

SECURE_SSL_REDIRECT = True

SECURE_HSTS_INCLUDE_SUBDOMAINS = True

SECURE_HSTS_PRELOAD = True

SECURE_HSTS_SECONDS = 1 #31536000

ALLOWED_HOSTS = ["127.0.0.1"] 

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # add rest_framework support to the project
    'rest_framework',
    # setting cors policy is needed to make calls from ui to api
    'corsheaders',
    'mauth'
]

MIDDLEWARE = [
    # Add cors middleware
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    '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',
]

ROOT_URLCONF = 'm.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "frontend")],
        '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 = 'm.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',
    }
}"""


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ["POSTGRES_NAME"],
        'USER': os.environ["POSTGRES_USER"],
        'PASSWORD': os.environ["POSTGRES_PASSWORD"],
        'HOST': os.environ["POSTGRES_HOST"],
        'PORT': os.environ["POSTGRES_PORT"],
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

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',
    },
]


# 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/'

STATICFILES_DIRS = [
  # Tell Django where to look for React's static files (css, js)
  os.path.join(BASE_DIR, "frontend/static"),
]

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# 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_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1',
]

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'mauth.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

对于我正在使用的前端:

  config["headers"]["Access-Control-Allow-Origin"] = ENV.API_URL
  config["headers"]["Access-Control-Allow-Credentials"] = 'true'

fetch(ENV.API_URL+url, config)

最佳答案

您不必在前端使用 header 等执行任何操作。 您只需确保 Django(后端)允许来自运行前端的主机的请求。

您已添加'http://127.0.0.1',它是后端的主机,(如果它们不在同一主机上运行,​​但您必须添加端口?)

因此,使用django-cors-headers,您可以执行以下操作:

假设后端正在 api.mysite.com 上运行 该前端正在 mysite.com 上运行(使用 HTTPS)

然后在settings.py中添加以下内容:

CORS_ALLOWED_ORIGIN_REGEXES = [
    r'^https:\/\/mysite.com$',
]

如果您想允许从本地主机进行开发,那么还要添加,这将允许从本地主机在任何端口上:

r'^http:\/\/localhost:\d+$',

关于javascript - 如何在 django Rest 框架中使用 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69615392/

相关文章:

javascript - 使用select过滤表数据的问题

javascript - 将大型数据集加载到 crossfilter/dc.js

python - 如何在linux中执行python文件

python - Django 数据库路由

mysql - Django 模型 : Inverted index on timestamp with query for 'n' latest rows

python - Django - 身份验证,使用电子邮件确认注册

javascript - 空闲时滚动?

javascript - 使用函数来管理 Backbone 中的关系

python 3 : check if method is static

python - MYSQL中如何按列分组两次