javascript - 如何在 django rest 框架中使用 CORS?
问题描述
我已经习惯但无法以django-cors-headers
正确的方式开始工作。CORS
CORS
就像从客户端一样,我可以从不在 ALLOWED HOSTS 中的任何主机运行代码,但请求仍然可以完成而没有任何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)
解决方案
您不必在前端使用标头等做任何事情。您只需确保 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+$',
推荐阅读
- c++ - 用于 STL 容器的 std::string_view
- easeljs - 位图缓存作为图像源
- perl - 子程序未返回正确的整数
- html - PrimeNG 切换按钮图标
- bots - 需要 DialogFlow 提示语句中的建议
- ms-access - 在 Access 的组合框中显示带有破折号的社会保险号
- vue.js - 如何在插槽中定义一个组件,该组件作为子组件中定义的道具
- angular - 如何使用角度谷歌地图显示多个标记 - 角度 6
- angular - ng2-ckeditor 中的自定义函数
- sql - ORA-12505, TNS:listener 目前不知道 11g 中连接描述符中给出的 SID