【问题标题】:How can I enable CORS on Django REST Framework如何在 Django REST 框架上启用 CORS
【发布时间】:2016-06-16 02:46:57
【问题描述】:

如何在我的 Django REST 框架上启用 CORS? reference 没有多大帮助,它说我可以通过中间件来做,但我该怎么做呢?

【问题讨论】:

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


    【解决方案1】:

    您在问题中引用的链接建议使用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_ 设置。您需要根据自己的需要设置其中的一些。

    【讨论】:

    • 你知道其他方法可以做到这一点,而无需安装新的依赖项吗?我现在正在尝试创建一个中间件类
    • @JulioMarins,你为什么要编写自己的版本,因为它很容易获得并且易于安装,有 12 个版本,21 个贡献者,超过 800 颗星和超过 100 个分叉?
    • 您确实有一点道理,但是由于只需要一个简单的 CORS 是一个标题 Access-Control-Allow-Origin: * 我不明白为什么要加载整个东西,我会在你的回答所以这两种方法都可以使用。参考:[链接(]enable-cors.org/server.html
    • @JulioMarins,这将是大锤方法。如果您查看我提供的配置链接,您会发现django-cors-headers 比这灵活得多。如果您想创建自己的课程,请成为我的客人。但我会使用那个库。
    • @Chris 我认为您应该添加 CORS_ORIGIN_WHITELIST 以便将呼叫主机列入白名单。
    【解决方案2】:
    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

    阅读官方文档几乎可以解决所有问题

    【讨论】:

    • 添加您添加到@Chris 的答案的四行对于我来说是必要的。
    • 为什么是CORS_ORIGIN_ALLOW_ALL = True,但是CORS_ORIGIN_WHITELIST还是设置了? The docs 似乎使这似乎不是必需的,并且似乎在这里的答案令人困惑。
    • CORS_ORIGIN_ALLOW_ALL 如果为 True,则不会使用白名单,将接受所有来源。
    • 还请记住,'corsheaders.middleware.CorsMiddleware', 需要位于列表的顶部,否则连接可能会在到达之前被拒绝。
    • CORS_ORIGIN_ALLOW_ALL = True,这成功了。
    【解决方案3】:

    您可以使用自定义中间件来做到这一点,即使知道最好的选择是使用包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
    )
    

    【讨论】:

    • 谢谢胡里奥!您的中间件代码应使用@masnun 代码示例进行更新。此外,导入对我不起作用,从 .修复问题:from . import corsMiddleware
    【解决方案4】:

    如果有人回到这个问题并决定编写自己的中间件,这是 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
    

    【讨论】:

      【解决方案5】:

      对于 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'
      ]
      

      简单易懂!

      【讨论】:

      • 之前发布的方法使用 MIDDLEWARE_CLASSES 而不是 MIDDLEWARE。这种技术有效,因此不需要投票:) @JulioMarins
      • 老兄,解决方法是一样的。您正在争论 Django 版本的实现。您的代码在open_access_middleware 上也有错误的缩进。
      【解决方案6】:

      以下是不需要任何外部模块的工作步骤:

      第 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 模块的应用名称。

      您现在可以验证它将向项目中的所有视图添加所需的响应标头!

      【讨论】:

      • 谢谢!我错过了 Access-Control-Allow-Headers 标头。
      【解决方案7】:

      嗯,我不认识,但是:

      在这里使用 python 3.6 和 django 2.2

      在 settings.py 中将 MIDDLEWARE_CLASSES 重命名为 MIDDLEWARE 有效。

      【讨论】:

        【解决方案8】:

        2021 年更新适用于所有拥有最新版本 Django v3.x.x 的人,下面给出了允许来自任何来源的 CORS 的步骤。

        第 1 步:安装所需的库

        pip install django-cors-headers
        

        第 2 步:然后在 setting.pyINSTALLED_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
        )
        

        【讨论】:

          【解决方案9】:

          首先安装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 错误。快乐编码

          【讨论】:

            【解决方案10】:

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

            【讨论】:

              猜你喜欢
              • 2021-12-05
              • 2018-10-17
              • 2018-08-20
              • 2021-08-22
              • 2019-01-09
              • 2019-02-14
              • 2021-04-29
              • 1970-01-01
              • 2015-07-26
              相关资源
              最近更新 更多