I'm trying to make a simple API using Django. I have setup a django server, and then on my own html file I send requests using $.getJSON
. So far it's been working using the django cors headers package.
Now I've been trying to send a request header to my django server, but I'm getting this error in the Chrome console:
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.
I'm not sure what's the problem, I have django-cors setup correctly and I am able to make requests, I'm just not allowed to set request headers.
Setup:
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)
So what am I doing wrong? Does django-cors not support this? I tried looking it up but I could not find anything. Thanks.
CodePudding user response:
From documentation for django-cors-headers
on PyPI it looks like you need to set the CORS_ALLOW_HEADERS
like so:
CORS_ALLOW_HEADERS = [
...
"Example-Header",
...
]
https://pypi.org/project/django-cors-headers/
If you want to dive deeper into CORS here is a thorough documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS