【发布时间】:2022-06-25 15:29:37
【问题描述】:
我正在尝试使用 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 不支持这个吗?我试图查找它,但我找不到任何东西。谢谢。
【问题讨论】:
标签: json django cors getjson django-cors-headers