53

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,385
  • 7
  • 26
  • 52
SPatrick
  • 541
  • 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

13 Answers13

93

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
  • 1,119
  • 8
  • 5
57

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.

Outsider
  • 1,166
  • 1
  • 14
  • 27
zxt077
  • 579
  • 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.
  • 1,048
  • 1
  • 13
  • 20
3

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
            }
        )

UPDATE

add the following code to settings.py

# <myproject/setting.py>
from .DEFAULT import DEFAULT_HEADERS

...
CORS_ALLOW_HEADERS = DEFAULT_HEADERS 


and in DEFAULTS.py

# <myproject/DEFAULTS.py>
from corsheaders.defaults import default_headers


DEFAULT_HEADERS = list(default_headers) + [
    "WWW-Authenticate",
    "Authorization",
    "Proxy-Authenticate",
    "Proxy-Authorization",
    "Age",
    "Cache-Control",
    "Clear-Site-Data",
    "Expires",
    "Pragma",
    "Warning",
    "Accept-CH",
    "Accept-CH-Lifetime",
    "Sec-CH-UA",
    "Sec-CH-UA-Arch",
    "Sec-CH-UA-Bitness",
    "Sec-CH-UA-Full-Version",
    "Sec-CH-UA-Full-Version-List",
    "Sec-CH-UA-Mobile",
    "Sec-CH-UA-Model",
    "Sec-CH-UA-Platform",
    "Sec-CH-UA-Platform-Version",
    "Content-DPR",
    "Device-Memory",
    "DPR",
    "Viewport-Width",
    "Width",
    "Downlink",
    "ECT",
    "RTT",
    "Save-Data",
    "Last-Modified",
    "ETag",
    "If-Match",
    "If-None-Match",
    "If-Modified-Since",
    "If-Unmodified-Since",
    "Vary",
    "Connection",
    "Keep-Alive",
    "Accept",
    "Accept-Encoding",
    "Accept-Language",
    "Expect",
    "Max-Forwards",
    "Cookie",
    "Set-Cookie",
    "Access-Control-Allow-Origin",
    "Access-Control-Allow-Credentials",
    "Access-Control-Allow-Headers",
    "Access-Control-Allow-Methods",
    "Access-Control-Expose-Headers",
    "Access-Control-Max-Age",
    "Access-Control-Request-Headers",
    "Access-Control-Request-Method",
    "Origin",
    "Timing-Allow-Origin",
    "Content-Disposition",
    "Content-Length",
    "Content-Type",
    "Content-Encoding",
    "Content-Language",
    "Content-Location",
    "Forwarded",
    "X-Forwarded-For",
    "X-Forwarded-Host",
    "X-Forwarded-Proto",
    "Via",
    "Location",
    "From",
    "Host",
    "Referer",
    "Referrer-Policy",
    "User-Agent",
    "Allow",
    "Server",
    "Accept-Ranges",
    "Range",
    "If-Range",
    "Content-Range",
    "Cross-Origin-Embedder-Policy",
    "Cross-Origin-Opener-Policy",
    "Cross-Origin-Resource-Policy",
    "Content-Security-Policy",
    "Content-Security-Policy-Report-Only",
    "Expect-CT",
    "Feature-Policy",
    "Origin-Isolation",
    "Strict-Transport-Security",
    "Upgrade-Insecure-Requests",
    "X-Content-Type-Options",
    "X-Download-Options",
    "X-Frame-Options",
    "X-Permitted-Cross-Domain-Policies",
    "X-Powered-By",
    "X-XSS-Protection",
    "Sec-Fetch-Site",
    "Sec-Fetch-Mode",
    "Sec-Fetch-User",
    "Sec-Fetch-Dest",
    "Service-Worker-Navigation-Preload",
    "Last-Event-ID",
    "NEL",
    "Ping-From",
    "Ping-To",
    "Report-To",
    "Transfer-Encoding",
    "TE",
    "Trailer",
    "Sec-WebSocket-Key",
    "Sec-WebSocket-Extensions",
    "Sec-WebSocket-Accept",
    "Sec-WebSocket-Protocol",
    "Sec-WebSocket-Version",
    "Accept-Push-Policy",
    "Accept-Signature",
    "Alt-Svc",
    "Date",
    "Early-Data",
    "Large-Allocation",
    "Link",
    "Push-Policy",
    "Retry-After",
    "Signature",
    "Signed-Headers",
    "Server-Timing",
    "Service-Worker-Allowed",
    "SourceMap",
    "Upgrade",
    "X-DNS-Prefetch-Control",
    "X-Firefox-Spdy",
    "X-Pingback",
    "X-Requested-With",
    "X-Robots-Tag",
    "X-UA-Compatible",
    "ContentType",
    "Content-type",
    "content-type",
    "contenttype",
    "contentType",


    "accept",
    "authorization",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",

    "accept-encoding",

    "Contentype",
]
Bambier
  • 586
  • 10
  • 16
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,626
  • 16
  • 15
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
  • 384
  • 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
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
  • 642
  • 6
  • 15
  • 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,553
  • 11
  • 22
0

Could not make it work after trying everything mentioned here. In fact, everything mentioned in the django-cors-headers documentation was already there in my settings.py.

After a lot of digging in, I found out the culprit was the "MIDDLEWARE" definition itself in settings.py. According to my version of django (which is 1.7) it needs to be "MIDDLEWARE_CLASSES" and not "MIDDLEWARE". You can find this out when you look at the django documentation for middlewares which can be found here https://docs.djangoproject.com/en/1.8/topics/http/middleware/ (don't forget to choose your version of django from right bottom corner). When this change was done, my preflights started returning the needed response headers.

Still scratching my head thinking how simple was the solution (when found out) for an issue which took hours away from me :(

Anoop Kc
  • 147
  • 1
  • 9
  • The answer is presupposed on the idea that they are using an outdated version of Django, which is incorrect. It is probably pertinent to ask the original poster which version of Django they are using and go from there. – Ananth Nov 19 '22 at 10:45
  • @Ananth admit, the issue cost me a fair amount of time. This is just another dimension that people can look into. Thought of posting it here because there can be people like me digging in without even thinking of this dimension – Anoop Kc Nov 22 '22 at 06:48
  • Which is exactly why it should be a comment on the question and not an answer. If the poster does use an outdated Django, then you would post this as an answer. – Ananth Nov 23 '22 at 02:04
-1

VERY IMPORTANT SETTINGS THAT MAKES CORS ERROR WORK

After adding all the above , please please make sure to add this,

For me this worked, I have added all the above, and it did not work,

Added the following line in settings.py, it worked, ( In addition to all the code that's put in settings.py )

CORS_ALLOW_HEADERS = "*"

indianwebdevil
  • 4,879
  • 7
  • 37
  • 51
-2

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,130
  • 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