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

时间:2018-08-01 18:15:28

标签: python django django-rest-framework python-3.6 django-cors-headers

我正在尝试将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

2 个答案:

答案 0 :(得分: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',
)

答案 1 :(得分:0)

django-cors-headers相当简单,我的配置似乎正确。

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

More info on CORS