Django Cors 允许访问控制允许标头

Joh*_*Doe 4 django json getjson cors django-cors-headers

我正在尝试使用 Django 制作一个简单的 API。我已经设置了一个 django 服务器,然后在我自己的 html 文件上使用$.getJSON. 到目前为止,它一直在使用django cors headers package进行工作。

现在我一直在尝试将请求标头发送到我的 django 服务器,但我在 Chrome 控制台中收到此错误:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/?q=example+query' from origin 'http://localhost:63342' has been blocked by CORS policy: Request header field Example-Header is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)

我不确定问题是什么,我的 django-cors 设置正确并且我能够发出请求,只是不允许设置请求标头。

设置:

INSTALLED_APPS = [
    ...
    'corsheaders',
]
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]
CORS_ALLOWED_ORIGINS = [
    "http://localhost:63342"
]
Run Code Online (Sandbox Code Playgroud)
<script>
   $.ajaxSetup({
      beforeSend: function(request) {
         request.setRequestHeader("Example-Header", 'Example-Value');
      },
   });
   $.getJSON("http://127.0.0.1:8000/api/?q=example+query", function (data) {
      console.log(data);
   });
</script>
Run Code Online (Sandbox Code Playgroud)
@cache_page(60 * 60 * 24 * 7)
def ExampleAPI(request):
    if request.method == 'GET':
       print(request.headers['Example-Header']) # Print Header Value 
       print(request.GET.get('q')) # Print URL Query Parameter Value   
       return JsonResponse([{"Example-Response": "Example-Response-Value"}], safe=False) 
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?django-cors不支持这个吗?我尝试查找,但找不到任何东西。谢谢。

小智 7

从 PyPI 的文档来看,django-cors-headers您似乎需要CORS_ALLOW_HEADERS这样设置:

CORS_ALLOW_HEADERS = [
    ...
    "Example-Header",
    ...
]
Run Code Online (Sandbox Code Playgroud)

https://pypi.org/project/django-cors-headers/

如果您想深入了解 CORS,这里有一份完整的文档: https: //developer.mozilla.org/en-US/docs/Web/HTTP/CORS