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

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'
]
πŸ‘€Clevison Luiz

58πŸ‘

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.

πŸ‘€zxt077

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.

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

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.

πŸ‘€Pansul Bhatt

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

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

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

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)

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

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

-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/
πŸ‘€Asha Niwale

-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

πŸ‘€Ajay Aneja

Leave a comment