Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox

SPatrick picture SPatrick · Apr 12, 2017 · Viewed 45.2k times · Source

I have researched and read quite a few Stackoverflow posts on the same issue. None have resolved my issue.

My problem is that I am getting the "...No 'Access-Control-Allow-Origin' header is present on the requested resource..." error in my console.

I am using:

Chrome Version 57.0.2987.133 Firefox Version 52.0.2

Python 2.7 Django 1.11a1

AngularJS

I am using MAMP to serve my front-end Angular stuff, and the django server for the backend stuff.

In my django settings I have included the cors middleware and tried both the whitelist approach and just setting all to true:

MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

CORS_ORIGIN_ALLOW_ALL = True

On google chrome I still get this error:

localhost/:1 XMLHttpRequest cannot load {my endpoint url}. Redirect from {my endpoint url} to {my endpoint url with a } has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin {requesting url} is therefore not allowed access.

It works appropriately on Firefox, and I can't figure out why it won't work for google chrome. I haven't tried any other types of browsers. Any help will be very appreciated, thank you.

Answer

Clevison Luiz picture Clevison Luiz · Jul 28, 2017

Install the cors-headers package with

pip install django-cors-headers

Adds to your installed apps

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

Add on your MIDDLEWARE remember to add as being the first in the list

MIDDLEWARE = [  
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

Before installed apps put this configuration for anyone to access

CORS_ORIGIN_ALLOW_ALL=True

Or create a list of hits

CORS_ORIGIN_WHITELIST = [
    'http://google.com',
    'http://hostname.example.com',
    'http://localhost:8000',
    'http://127.0.0.1:9000'
]