【发布时间】:2016-06-16 02:46:57
【问题描述】:
如何在我的 Django REST 框架上启用 CORS? reference 没有多大帮助,它说我可以通过中间件来做,但我该怎么做呢?
【问题讨论】:
标签: python django cors django-rest-framework middleware
如何在我的 Django REST 框架上启用 CORS? reference 没有多大帮助,它说我可以通过中间件来做,但我该怎么做呢?
【问题讨论】:
标签: python django cors django-rest-framework middleware
您在问题中引用的链接建议使用django-cors-headers,其documentation 表示要安装库
python -m pip install django-cors-headers
然后将其添加到您安装的应用程序中:
INSTALLED_APPS = (
...
'corsheaders',
...
)
您还需要添加一个中间件类来监听响应:
MIDDLEWARE = [
...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...,
]
并为 CORS 指定域,例如:
CORS_ALLOWED_ORIGINS = [
'http://localhost:3030',
]
请浏览其文档中的the configuration section,特别注意各种CORS_ORIGIN_ 设置。您需要根据自己的需要设置其中的一些。
【讨论】:
Access-Control-Allow-Origin: * 我不明白为什么要加载整个东西,我会在你的回答所以这两种方法都可以使用。参考:[链接(]enable-cors.org/server.html)
django-cors-headers 比这灵活得多。如果您想创建自己的课程,请成为我的客人。但我会使用那个库。
python -m pip install django-cors-headers
然后将其添加到您安装的应用程序中:
INSTALLED_APPS = [
...
'corsheaders',
...
]
您还需要添加一个中间件类来监听响应:
MIDDLEWARE = [
...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...,
]
CORS_ALLOW_ALL_ORIGINS = True # If this is used then `CORS_ALLOWED_ORIGINS` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
'http://localhost:3030',
] # If this is used, then not need to use `CORS_ALLOW_ALL_ORIGINS = True`
CORS_ALLOWED_ORIGIN_REGEXES = [
'http://localhost:3030',
]
更多详情:https://github.com/ottoyiu/django-cors-headers/#configuration
阅读官方文档几乎可以解决所有问题
【讨论】:
CORS_ORIGIN_ALLOW_ALL = True,但是CORS_ORIGIN_WHITELIST还是设置了? The docs 似乎使这似乎不是必需的,并且似乎在这里的答案令人困惑。
'corsheaders.middleware.CorsMiddleware', 需要位于列表的顶部,否则连接可能会在到达之前被拒绝。
您可以使用自定义中间件来做到这一点,即使知道最好的选择是使用包django-cors-headers 的测试方法。话虽如此,这里是解决方案:
创建以下结构和文件:
-- myapp/middleware/__init__.py
from corsMiddleware import corsMiddleware
-- myapp/middleware/corsMiddleware.py
class corsMiddleware(object):
def process_response(self, req, resp):
resp["Access-Control-Allow-Origin"] = "*"
return resp
添加到settings.py标记的行:
MIDDLEWARE_CLASSES = (
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
# Now we add here our custom middleware
'app_name.middleware.corsMiddleware' <---- this line
)
【讨论】:
from . import corsMiddleware
如果有人回到这个问题并决定编写自己的中间件,这是 Django 新型中间件的代码示例 -
class CORSMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
return response
【讨论】:
对于 Django 版本 > 1.10,根据documentation,可以将自定义 MIDDLEWARE 编写为函数,让我们在文件中说:yourproject/middleware.py(作为settings.py 的兄弟):
def open_access_middleware(get_response):
def middleware(request):
response = get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
return response
return middleware
最后,将此函数的 python 路径(w.r.t. 项目的根目录)添加到项目settings.py 的 MIDDLEWARE 列表中:
MIDDLEWARE = [
.
.
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'yourproject.middleware.open_access_middleware'
]
简单易懂!
【讨论】:
open_access_middleware 上也有错误的缩进。
以下是不需要任何外部模块的工作步骤:
第 1 步:在您的应用中创建一个模块。
例如,假设我们有一个名为 user_registration_app 的应用。探索 user_registration_app 并创建一个新文件。
我们将其称为 custom_cors_middleware.py
粘贴下面的类定义:
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
第 2 步:注册中间件
在你的项目 settings.py 文件中,添加这一行
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'
例如:
MIDDLEWARE = [
'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
...
'django.middleware.common.CommonMiddleware',
]
记得将 user_registration_app 替换为您在其中创建 custom_cors_middleware.py 模块的应用名称。
您现在可以验证它将向项目中的所有视图添加所需的响应标头!
【讨论】:
嗯,我不认识,但是:
在这里使用 python 3.6 和 django 2.2
在 settings.py 中将 MIDDLEWARE_CLASSES 重命名为 MIDDLEWARE 有效。
【讨论】:
2021 年更新适用于所有拥有最新版本 Django v3.x.x 的人,下面给出了允许来自任何来源的 CORS 的步骤。
第 1 步:安装所需的库
pip install django-cors-headers
第 2 步:然后在 setting.py 的 INSTALLED_APPS 中的适当位置添加 - 在 rest_framework 之后和您的应用程序之前 myapp
'rest_framework',
'corsheaders',
'myapp.apps.MyAppConfig',
第 3 步:允许您的 api 的来源
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000', # for localhost (REACT Default)
'http://192.168.10.45:3000', # for network
)
【讨论】:
首先安装django包
pip install django-cors-headers
并添加到设置文件中的应用程序
INSTALLED_APPS = (
...
'corsheaders',
...
)
然后将cors中间件添加到设置文件中
MIDDLEWARE = [
...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...,
]
最后添加跨域白名单
#CORS_ORIGIN_ALLOW_ALL = True
#CORS_ALLOW_CREDENTIALS = True
#CORS_ALLOW_HEADERS = ['*']
CORS_ORIGIN_WHITELIST = ('http://localhost:5000',)
这将很容易解决 cors 错误。快乐编码
【讨论】:
Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0
按照官方说明不行
最后还是用老办法弄明白了。
添加:
# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return # To not perform the csrf check previously happening
#proj/settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'proj.middlewares.CsrfExemptSessionAuthentication',
),
}
【讨论】: