django-cors-headers 不工作:请求的资源上不存在 'Access-Control-Allow-Origin' header

django-cors-headers not working: No 'Access-Control-Allow-Origin' header is present on the requested resource

完整错误:

Access to XMLHttpRequest at 'https://[redacted]/api/get_match_urls/' from origin 'https://trello.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我正在 trello.com

从分机拨打 API 电话

我的 INSTALLED_APPS 中有 corsheaders。我的中间件中有 'corsheaders.middleware.CorsMiddleware' 尽可能高。我将 CORS_ORIGIN_ALLOW_ALL 设置为 True。是的,我已经尝试了备用别名 CORS_ALLOW_ALL_ORIGINS,但仍然没有用。有人有什么想法吗?

MIDDLEWARE = [
    
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我查看了 corsheaders.middleware.CorsMiddleware,似乎如果您设置 CORS_ALLOW_ALL_ORIGINS 而不是 CORS_ALLOW_CREDENTIALS,它将 return Access-Control-Allow-Origin: *,但是如果您还设置 CORS_ALLOW_CREDENTIALS 然后它将 return 来自请求的来源 headers.

这是执行此操作的代码部分

origin = request.META.get("HTTP_ORIGIN")

# omiting the lines in between

if conf.CORS_ALLOW_ALL_ORIGINS and not conf.CORS_ALLOW_CREDENTIALS:
    response[ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
else:
    response[ACCESS_CONTROL_ALLOW_ORIGIN] = origin

另一个想法也是使用 CORS_ALLOWED_ORIGIN_REGEXES 例如

CORS_ALLOWED_ORIGIN_REGEXES = [
    r".*",
]