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

Solution 1:

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'
]

Solution 2:

Check your request URL first. I had this problem when while using vue-resource. In my case, the error was a missing '/' at the end of url.

Solution 3:

Make sure use 127.0.0.1 NOT localhost because when using localhost browser may look up an IPv6 address... or set up localhost to explicitly to 127.0.0.1 at /etc/hosts

Solution 4:

Perhaps you need to take a look at how you are calling your middlewares. If they are not in the correct sequence they might throw this error. It seems like your 'django.middleware.security.SecurityMiddleware' needs to be pushed below the 'corsheaders.middleware.CorsMiddleware'. Also, it looks like you might have to add CORS_ALLOW_CREDENTIALS = True in your code as well.

Hope this helps.

Solution 5:

I was fighting with this CORS issue when making a GET call from my Angular-app. After 1-2 hours looking at this error from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It just turned out that my URL was invalid. I was missing a single / from the end of the URL. I actually tried every answer...

See also: Django CORS API from AngularJS

edit: After looking at the server log I can see that HTTP 301 was returned on every failed call. Django returning HTTP 301?

edit2: might also be helpful: https://docs.djangoproject.com/en/dev/ref/settings/#append-slash