44

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.

T-Heron
  • 5,202
  • 7
  • 24
  • 49
SPatrick
  • 451
  • 1
  • 4
  • 4
  • I am having this problem too -- it works in FF but not Chrome. I have the corsheaders in my INSTALLED_APPS and the two lines mentioned in the MIDDLEWARE, and I've got CORS_ORIGIN_WHITELIST set to a list with 'http://localhost:8080' as the first item. I've also tried adding the following headers to the JSONResponse: def set_cors_headers(rsp: JSONResponse, method: str)->JSONResponse: rsp.__setitem__("Access-Control-Allow-Origin", "*") rsp.__setitem__("Access-Control-Allow-Methods", method) rsp.__setitem__("Access-Control-Allow-Headers", "*") return rsp – Steve L Feb 17 '20 at 15:09

11 Answers11

81

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'
]
Community
  • 1
  • 1
Clevison Luiz
  • 971
  • 6
  • 4
49

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.

Arka Ghosh
  • 1,020
  • 1
  • 14
  • 27
zxt077
  • 499
  • 4
  • 5
7

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

Pay C.
  • 944
  • 1
  • 11
  • 20
2

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

O-9
  • 1,315
  • 13
  • 13
1

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.

Pansul Bhatt
  • 344
  • 2
  • 5
  • Thanks, but i'm still having the same issue. An update though: I have two endpoints that I am trying to hit, and in my views.py, serializers.py, and urls.py they are created exactly the same, the only difference really is the models. The 2nd of my two endpoints is working properly in chrome, but the first is still throwing the cors headers error described above. Both work as intended in firefox. – SPatrick Apr 14 '17 at 00:09
  • This is kind of peculiar. Are we sure that all the packages have been installed properly or some dependency that has been missed. Ideally you adding 'corsheaders.middleware.CorsMiddleware' should have worked. – Pansul Bhatt Apr 17 '17 at 06:26
1

In my case, First of all make sure if you apply all these settings. then if you use axios or same things in frontend make sure that you define METHOD in options.

‌‌ ‌ ‌ ‌ ‌ ‌ python -m pip install django-cors-headers

django

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

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

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

js

const options = {
        url: "http://localhost:8000/blog/v1/",
        // buttom sections 
        method: "GET", 
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8'
          },
        // top section
        
    };
    axios(options)
        .then(
            response => {
                return response.data
            }
        )
Nima
  • 147
  • 1
  • 8
0

the reason that is chrome browse; you can install CORS Toggle app in chrome or deploy your web code to nginx or apache then using chrome.

cece
  • 1
  • 1
0

Old question, but I'm not seeing this solution, which worked for me, anywhere. So hoping this can be helpful for someone.

Cross-origin requests in this context are only possible if the partner site's server allows it through their response headers.

I got this to work in Django without any CORS middleware by setting the following headers on the response:

    response["Access-Control-Allow-Origin"] = "requesting_site.com"
    response["Access-Control-Allow-Methods"] = "GET"
    response["Access-Control-Allow-Headers"] = "requesting_site.com"

Most answers on StackOverflow seem to mention the first one, but not the second two. I've just confirmed they are all required. You'll want to modify as needed for your framework or request method (GET, POST, OPTION).

p.s. You can try "*" instead of "requesting_site.com" for initial development just to get it working, but it would be a security hole to allow every site access. Once working, you can restrict it for your requesting site only to make sure you don't have any formatting typos.

Joel Wigton
  • 483
  • 5
  • 11
  • Actually you are solution worked for me with reverse. I have removed you mentioned code in frontend, the application worked well. – Sathiamoorthy Sep 24 '20 at 08:11
  • @Shakthifuture Glad it worked for you. If so, consider an upvote to give the answer more weight. That's how this works. :-) – Joel Wigton Sep 25 '20 at 16:40
0

In settings.py

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

            'corsheaders',
             #...
            ]
# Set CORS_ORIGIN_ALLOW_ALL is True

CORS_ORIGIN_ALLOW_ALL = True  # this allows all domains

#Or to allow specific domains 

 CORS_ORIGIN_WHITELIST = (
'http://example.com',
'http://127.0.0.1:8000',
'http://localhost:8000',
)

Along with your configurations, you should add headers in frontend call:

 var get_request = $.ajax({
 type: 'GET',
 "headers": {
      "accept": "application/json",
      "Access-Control-Allow-Origin":"*"
  },
 url: 'http://example.com',
 });

If it is not solved, You should enable the core in requesting server(http://example.com)

Ramesh Ponnusamy
  • 1,031
  • 7
  • 16
-1

see if your url is correct. For me it works by doing following things:

  1. install django cors headers package # django-cors-headers
  2. Add CORS_ORIGIN_ALLOW_ALL = True in settings.py
  3. Add this two line in start at MIDDLEWARE tag corsheaders.middleware.CorsMiddleware django.middleware.common.CommonMiddleware
  4. add below line into INSTALLED_APPS corsheader
  5. And added back slash at the end of url like http://127.0.0.1:8000/getcust/
Hoppo
  • 1,070
  • 1
  • 13
  • 32
-3

You can install django-cors-headers app and in the settings.py you should put 'corsheaders' in the INSTALLED_APPS and

'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

in the starting of the MIDDLEWARE of the settings

The README of the Github link explains the details

  • Since i see that you have Middleware settings.I assume you have already installed the corsheaders. Just make sure 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', are in the top of the MiddleWare settings – Ajay Aneja Apr 14 '17 at 11:50
  • Not what the official documentation says...django's `SecurityMiddleware` and `SessionMiddleware` should always be on top for security reasons... – Noopur Phalak Apr 19 '22 at 04:03