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

django-cors-headers dont work with DRF(Django Rest Framework)

我正在尝试将 django-cors-headers 添加到我的 django rest API 以在响应 object 中添加 HTTP header 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

我正在使用:

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

django-cors-headers 是合理的 fool-proof,你的配置对我来说似乎是正确的。

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

More info on CORS

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

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

  2. 编辑您的 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