pythondjangocorsdjango-cors-headers

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?


Solution

  • 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'
    )