简体   繁体   中英

Django Localhost CORS not working

I have a local Django setup as follows

Django Rest Framework : localhost:8000

AngularJS frontend : local apache running on http://localservername

I've installed django-cors-headers and in my settings.py , I've setup my

CORS_ORIGIN_WHITELIST = (
    'http://localhost',
    'localservername',
    'http://localservername',
    '127.0.0.1'
)


MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

However, I get a No 'Access-Control-Allow-Origin' header is present on the requested resource. error whenever I hit any API that's served from the Rest Framework . If I set CORS_ORIGIN_ALLOW_ALL = True , then the API's work correctly but that's highly insecure for my server side data.

What do I have to change to fix this?

Here in this error the hint is clearly mentioning that it needs https://

HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com).

Moreover, it is also true that braces matters in django settings.

CORS_ORIGIN_WHITELIST = [
    'https://localhost:3000'
]

And the above settings work fine.

While the same settings with different brackets won't work

CORS_ORIGIN_WHITELIST = (
    'https://localhost:3000'
)

For me i used [] instead of (). Also don't add a '/' at the end url.

Something like this

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000'
]

I had the same problem. By browsing the django-cors-headers -code found my mistake was the following:

While a complete CORS-header looks like this (notice schema AND hostname):

Access-Control-Allow-Origin: https://example.com

The CORS_ORIGIN_WHITELIST setting wants it in a format that compares to urlparse.netloc (docs ) of the Origin -header, which is only the host (possibly the port)

def origin_found_in_white_lists(self, origin, url):
    return (
        url.netloc in conf.CORS_ORIGIN_WHITELIST or
        (origin == 'null' and origin in conf.CORS_ORIGIN_WHITELIST) or
        self.regex_domain_match(origin)
    )

While the RegEx-whitelist compares it against the complete Origin -header.

So the correct setting (as the example in the setup-manual correctly states, but not properly describes) would be:

CORS_ORIGIN_WHITELIST = (
    'example.com',
)

Which can be a problem if you do not want your API to talk to the non-secure http-version of a website. Use the RegEx in that case.

Also note: during troubleshooting I found out that the CORS-header is completely absent if no match is found. Which means that absence of the header is not a sure indication of a complete malfunction of the middleware, but maybe just a misconfiguration.

As per http://www.w3.org/Security/wiki/Same_Origin_Policy , the requests should be from same port, scheme, and host to be considered as same origin. Here one of your server is in port 80 and the other one is on 8080.

An origin is defined by the scheme, host, and port of a URL. Generally speaking, documents retrieved from distinct origins are isolated from each other. For example, if a document retrieved from http://example.com/doc.html tries to access the DOM of a document retrieved from https://example.com/target.html , the user agent will disallow access because the origin of the first document, (http, example.com, 80), does not match the origin of the second document (https, example.com, 443).

This works for me, Please check with this, it may help you to resolve your issue.

CORS_ORIGIN_WHITELIST = (
    'http://localhost',
)

Braces matter for me,use [] instead of (), I have verified in Django, others I haven't checked.

Write Like This:

CORS_ORIGIN_WHITELIST=[ ' https://localhost:3000 ' ]

CORS_ORIGIN_WHITELIST=[ ' https://localhost:3000 ' ] 它工作正常。

像 CORS_ORIGIN_WHITELIST = [ ' https://localhost:3000 ' ] 这样的写作对我来说效果很好。

Copy the whitelist code from the django-cors-headers documentation , and then just modify it:

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

That will guarantee you that you didn't make any typos.

Make sure that not to add path / , like following:

CORS_ORIGIN_WHITELIST = (
    'https://localhost:3000/'
)

Just add the following code instead.

CORS_ORIGIN_WHITELIST = [
    'https://localhost:3000'
]

maybe braces matter

[] instead of ()

CORS_ORIGIN_WHITELIST = [

    'http://localhost',

    'localservername',

    'http://localservername',

    '127.0.0.1'

]

should work

I think the best way to do solve this error is :-

  1. Type the URL in the browser, for eg :- If you are running an angular app, then do,

    ng serve

    and type the URL given by "ng serve" command into the browser. for eg :- localhost:4200

  2. then, Copy the URL from the browser and paste as it is in the cors allowed host. eg :-

    CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ]

Note :- Don't forget to Remove the last "/" sign from the URL, so instead of, http://localhost:4200/ add this :- http://localhost:4200

And after this, you'll see no error.

I fixed this by fixing the order in:

INSTALLED_APPS = [
...
'corsheaders',
'image_cropping',
'easy_thumbnails',
...
'rest_framework',
...
]






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

... ]

install Django cors package

django-cors-headers

go to settings.py and add it to installed apps

INSTALLED_APPS = [
    .....
    'corsheaders',
 ]

add it to the middleware

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


]

Most important step

add this right below the middleware without a slash at the end

CORS_ORIGIN_WHITELIST = ['http://localhost:3000']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM