django-cors-headers not work
INSTALLED_APPS = (
\'django.contrib.admin\',
\'django.contrib.auth\',
\'django.contrib.contenttypes\',
\'django.
Somehow django-cors-headers
would not work for me with Django 2
despite following all the steps. The pre-flight check would retrun a 405 error.
I ended up writing a small middleware:
from django import http
class CorsMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if (request.method == "OPTIONS" and "HTTP_ACCESS_CONTROL_REQUEST_METHOD" in request.META):
response = http.HttpResponse()
response["Content-Length"] = "0"
response["Access-Control-Max-Age"] = 86400
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "DELETE, GET, OPTIONS, PATCH, POST, PUT"
response["Access-Control-Allow-Headers"] = "accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with"
return response
Then added this middleware in my settings.py
:
MIDDLEWARE = [
'apps.core.middleware.CorsMiddleware',
... others below it
]
This did the trick for me.
For me I had to add non-standard headers. Even if CORS_ORIGIN_ALLOW_ALL = True
is set, it will still check if the headers are allowed.
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = list(default_headers) + [
'my-custom-header',
]
The same can be done for non-standard methods:
from corsheaders.defaults import default_methods
CORS_ALLOW_METHODS = list(default_methods) + [
'POKE',
]
Are you trying to use the url inside an iframe
?
If that is the case, then the header X-Frame-Options: SAMEORIGIN
might be causing a problem.
To fix it remove the middleware, django.middleware.clickjacking.XFrameOptionsMiddleware
.
I was having this same issue and everything seemed to be in the right place. Then I figured out that I had started the server before adding 'corsheaders.middleware.CorsMiddleware',
to the MIDDLEWARE_CLASSES
. After making the correction, it was still not working. After trying a bunch of stuff, I opened it in another browser and it worked. So it turned out that I just needed to clear the browser cache.
Final solution would be send response with CORS allowed headers.
response["Access-Control-Allow-Origin"] = "*"
response['Content-Type'] = "application/json; charset=utf-8"
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type, My-Token"
What I did was depreciate the version of django-cors-headers
for it to work.
I moved from version 3.2.1
to 2.4.0
. You can do that by installing the specific version using pip
pip install django-cors-headers==2.4.0