I have a local Django setup as follows
Django Rest Framework
:localhost:8000
AngularJS frontend
:local apache running on http://localservername
I've installed django-cors-headers
and in my settings.py
, I've setup my
CORS_ORIGIN_WHITELIST = (
'http://localhost',
'localservername',
'http://localservername',
'127.0.0.1'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
However, I get a No 'Access-Control-Allow-Origin' header is present on the requested resource.
error whenever I hit any API that's served from the Rest Framework
. If I set CORS_ORIGIN_ALLOW_ALL = True
, then the API's work correctly but that's highly insecure for my server side data.
What do I have to change to fix this?
django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).
The CORS behavior, commonly termed as CORS error, is a mechanism to restrict users from accessing shared resources. This is not an error but a security measure to secure users or the website which you are accessing from a potential security bleach.
Here in this error the hint is clearly mentioning that it needs https://
HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com).
Moreover, it is also true that braces matters in django settings.
CORS_ORIGIN_WHITELIST = [
'https://localhost:3000'
]
And the above settings work fine.
While the same settings with different brackets won't work
CORS_ORIGIN_WHITELIST = (
'https://localhost:3000'
)
For me i used [] instead of (). Also don't add a '/' at the end url.
Something like this
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With