Djangocorsheaders不工作:请求的资源上不存在“AccessControlAllowOrigin”头

2024-05-15 21:47:03 发布

您现在位置:Python中文网/ 问答频道 /正文

完全错误:

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调用

我的corsheaders中有INSTALLED_APPS。我的中间件中有尽可能高的'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',
]

Tags: todjangohttpscomaccess错误allcontrib
1条回答
网友
1楼 · 发布于 2024-05-15 21:47:03

我看了一下corsheaders.middleware.CorsMiddleware,似乎如果您设置了CORS_ALLOW_ALL_ORIGINS而不是CORS_ALLOW_CREDENTIALS,它将返回Access-Control-Allow-Origin: *,但是如果您也设置了CORS_ALLOW_CREDENTIALS,那么它将从请求头返回原点

下面是代码中实现这一点的部分

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".*",
]

相关问题 更多 >