【问题标题】:CORS header missing when project hosted in a Subpath项目托管在子路径中时缺少 CORS 标头
【发布时间】:2020-04-14 20:40:32
【问题描述】:

我有一个 Django(v2.2) 项目托管在一个 url 上,看起来像 https://some.example.com/mypath/ 的 API 端点位于 blog/create。 我需要从https://some.example.com/anotherpath/ofmine/(使用 axios)发出 POST 请求,但这给了我一个 301 错误,并在 Firefox 71.0 中显示以下消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS request did not succeed).

但是,我可以轻松地向本地托管的开发服务器发出相同的请求。

相关设置:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'rest_framework_docs',
    'corsheaders',                                                          
    'django_extensions',
    ...
]

USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/mypath'
CORS_ORIGIN_ALLOW_ALL = True

错误的原因和可能的解决方法是什么?

【问题讨论】:

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


    【解决方案1】:

    根据django-cors-headers 文档,您需要将CORS_ORIGIN_WHITELIST 设置为包含您的端点,或者将CORS_ORIGIN_ALLOW_ALL 设置为True 以允许所有主机(但不建议用于生产)。

    【讨论】:

    • 是的,已经有了;忘了在这里添加那部分代码。已编辑。
    【解决方案2】:

    愚蠢的错误。 some.example.com 重定向到www.some.example.com,所以我一直在尝试从www.some.example.com 访问some.example.com(不存在,因此是301)的API。在请求 url 上加上 www 前缀,它工作正常;当然,我什至不需要 CORS 标头。

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      相关资源
      最近更新 更多