Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Localhost CORS not working

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?

like image 313
Newtt Avatar asked Jan 10 '16 03:01

Newtt


People also ask

What is Corsheaders in Django?

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).

What are cors errors?

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.


2 Answers

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'
)
like image 66
S Habeeb Ullah Avatar answered Sep 30 '22 15:09

S Habeeb Ullah


For me i used [] instead of (). Also don't add a '/' at the end url.

Something like this

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000'
]
like image 20
user13872382 Avatar answered Sep 30 '22 13:09

user13872382