57

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.

1
  • 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 '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 Commented Feb 17, 2020 at 15:09

14 Answers 14

99

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'
]
Sign up to request clarification or add additional context in comments.

6 Comments

Did not work for me for django 2.1.4 and django-cors-headers 2.4.0 which are both the latest versions at the time of writing.
the question clearly states that he had installed cors-headers already and that the problem lies between Chrome and FF
Small correction, the last part should be with [ instead of (.
You must add "http://" for example as the error you'll give says: Origin 'localhost:3000' in CORS_ORIGIN_WHITELIST is missing scheme or netloc
as mentioned by @normic this is clearly not the proper answer to the question.
|
64

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.

6 Comments

Had the same issue and this was the fix for me. See also this post from '15(!) for details: stackoverflow.com/a/33377351/5745325
This is the solution. Should be accepted as answer.
This is the solution for me at least in Angular 2+
For Angular in my case, the URL had two slashes //. In that case, shouldn't it be the 404?
SAved my day using axios with vue
|
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

Comments

4

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",
]

Comments

2

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.

2 Comments

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.
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.
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

Comments

1

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)

Comments

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.

Comments

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.

2 Comments

Actually you are solution worked for me with reverse. I have removed you mentioned code in frontend, the application worked well.
@Shakthifuture Glad it worked for you. If so, consider an upvote to give the answer more weight. That's how this works. :-)
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 :(

3 Comments

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 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
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.
0

Faced the same issue even after correctly configuring django-cors-headers in my Django settings. After reading about CORS and how it works and how it rejects requests, I realized that the response headers weren't being sent from the server.

After looking into my Nginx configurations, I found that it was conflicting with Django's CORS settings. In my Nginx configuration, I had manually added the CORS headers like this:

add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
}

The issue was this line:

add_header 'Access-Control-Allow-Origin' *;

The * wildcard allows all origins, which conflicts with the Access-Control-Allow-Credentials: true header. When credentials are included in the request (e.g., cookies or HTTP authentication), the browser does not allow the wildcard (*) in Access-Control-Allow-Origin, and this leads to a CORS error.

The solution: I replaced the * with $http_origin to dynamically set the Access-Control-Allow-Origin header based on the request's Origin header. This allowed the server to only send the correct origin, as listed in Django’s CORS_ALLOWED_ORIGINS:

add_header 'Access-Control-Allow-Origin' $http_origin;

After these changes, the CORS error was solved, and it worked as expected for me. Maybe you should try checking your web server's configuration it could be an issue too.

Comments

-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 = "*"

1 Comment

@TD1 This is not CORS_ORIGIN_ALLOW_ALL = True # this allows all domains, This is to allow all headers only.
-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

2 Comments

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
Not what the official documentation says...django's SecurityMiddleware and SessionMiddleware should always be on top for security reasons...
-3

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.