我正在嘗試使用 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.
我不確定是什么問題,我已經正確設定了 django-cors 并且可以發出請求,只是不允許設定請求標頭。
設定:
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:63342"
]
<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>
@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)
那么我做錯了什么?django-cors 不支持這個嗎?我試圖查找它,但我找不到任何東西。謝謝。
uj5u.com熱心網友回復:
從django-cors-headers關于 PyPI 的檔案看來,您需要CORS_ALLOW_HEADERS像這樣設定:
CORS_ALLOW_HEADERS = [
...
"Example-Header",
...
]
https://pypi.org/project/django-cors-headers/
如果您想深入了解 CORS,這里有一個詳盡的檔案:https ://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426822.html
標籤:json django 科尔斯 获取json django-cors-headers
