django-cors-headers 不适用于 DRF(Django Rest 框架)

Posted

技术标签:

【中文标题】django-cors-headers 不适用于 DRF(Django Rest 框架)【英文标题】:django-cors-headers dont work with DRF(Django Rest Framework) 【发布时间】:2019-01-09 09:52:00 【问题描述】:

我正在尝试将 django-cors-headers 添加到我的 django rest API 以在响应对象中添加 HTTP 标头 Access-Control-Allow-Origin,但我没有设法使其工作。我已按照官方文档中的说明进行操作,但无法正常工作。

这是我的settings.py文件的内容:

... INSTALLED_APPS = [ 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'hvad', 'rest_framework.authtoken', 'rest_framework_swagger', 'accounts.apps.AccountsConfig', 'rest_auth', ] ... MIDDLEWARE:[ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... # CORS Config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False

我正在使用:

Django 1.11.14 django-cors-headers 2.4.0 djangorestframework 3.8.2 python 3.6.5 点 10.0.1 Windows 10

【问题讨论】:

你的问题不清楚。错误是什么?有什么问题? 对不起,如果我不清楚。我正在尝试使用 django-cors-headers 包在我的 REST API 的 Reponse 对象中添加一些 HTTP 标头,官方 DRF 文档建议使用此包来处理 CORS 这里是documentation 您遇到的错误是什么让您认为它不起作用? 我没有收到任何错误,只是我的 django-cors-headers 没有添加 HTTP 标头 Access-Control-Allow-Origin 最后它只在我创建一个新的中间件文件时才有效,这里是文件gist.github.com/fronzec/9098d57e3f1b36aeabd5c4927eafa90f 【参考方案1】:

如果您使用的是 Chrome,请使用 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

================================================ ===================================

CORS_URLS_REGEX = r'^/*$'

CORS_ALLOW_METHODS

实际请求允许的 HTTP 动词列表。默认为:

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

【讨论】:

【参考方案2】:

django-cors-headers 相当简单,您的配置对我来说似乎是正确的。

不过,我也遇到了一个问题: 如果您将服务器配置为在不调用 Django / Python 的情况下提供静态文件(很常见,即使在内置服务器上也是如此),django-cors-headers 无法将 CORS 标头应用于这些响应。 根据浏览器的不同,这会导致异步请求、字体甚至图像、视频和音频出现问题。

More info on CORS

【讨论】:

【参考方案3】:

最后。它仅在我创建新的中间件文件时才有效。这是我的中间件的内容:

    将此文件放在<your_app>/middleware/cors.py

    编辑您的 setting.py 以添加新的中间件

     # -*- coding:utf-8 -*-
    
     from django.http import HttpResponse
     from django.utils.deprecation import MiddlewareMixin
    
     class CorsMiddleware(MiddlewareMixin):
         def process_response(self, request, response):
             response["Acces-Control-Allow-Origin"] = "*"
             return response
    

【讨论】:

以上是关于django-cors-headers 不适用于 DRF(Django Rest 框架)的主要内容,如果未能解决你的问题,请参考以下文章

Django-cors-headers解决跨域问题

django-cors-headers

即使使用 django-cors-headers 也得到 304 响应

跨域设置django-cors-headers

使用 Postman 时 django-cors-header 无法按预期工作

django-cors-header 出现问题 - ModuleNotFoundError: No module named 'corsheaders'