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

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

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

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

... 已安装的应用程序 = [ '套装', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '休息框架', 'corsheaders', '哈瓦德', 'rest_framework.authtoken', 'rest_framework_swagger', 'accounts.apps.AccountsConfig', '休息验证', ] ... 中间件:[ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... # CORS 配置 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

最佳答案

如果您使用的是 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',
)

关于python - django-cors-headers 不适用于 DRF(Django Rest Framework),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51639826/

相关文章:

python - Airflow cron 表达式没有正确安排 dag

python - 从 pandas 的列中的值获取特定数量的数据

python - 在 Django 中创建和保存对象时需要管理器吗?

python - 使用 ChoiceField 时出现 Django Rest API TypeError

Python-bytes() 与 struct.pack()

python - 如何在 Flask 中提交其他表单后登录?

python - 无法在我的 django 1.5 模板中加载 css

python - 在 Django 模板中渲染外部定义的 block

python - 带有 generics.ListCreateAPIView 的 Django REST 框架外键

Django Rest Framework 在登录或注册后返回用户配置文件以及 api token