Django Python rest 框架,Chrome 中请求的资源上不存在“Access-Control-Allow-Origin”标头,可在 firefox 中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43357687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:56:59  来源:igfitidea点击:

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

pythondjangogoogle-chromedjango-rest-frameworkdjango-cors-headers

提问by SPatrick

I have researched and read quite a few Stackoverflow posts on the same issue. None have resolved my issue.

我已经研究并阅读了很多关于同一问题的 Stackoverflow 帖子。没有人解决我的问题。

My problem is that I am getting the "...No 'Access-Control-Allow-Origin' header is present on the requested resource..." error in my console.

我的问题是我在控制台中收到“...请求的资源上不存在'Access-Control-Allow-Origin'标头...”错误。

I am using:

我在用:

Chrome Version 57.0.2987.133 Firefox Version 52.0.2

Chrome 版本 57.0.2987.133 Firefox 版本 52.0.2

Python 2.7 Django 1.11a1

Python 2.7 Django 1.11a1

AngularJS

AngularJS

I am using MAMP to serve my front-end Angular stuff, and the django server for the backend stuff.

我使用 MAMP 来为我的前端 Angular 提供服务,并使用 django 服务器为后端提供服务。

In my django settings I have included the cors middleware and tried both the whitelist approach and just setting all to true:

在我的 Django 设置中,我包含了 cors 中间件,并尝试了白名单方法并将所有设置为 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.clickHymaning.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.

localhost/:1 XMLHttpRequest 无法加载 {my endpoint url}。从 {my endpoint url} 重定向到 {my endpoint url with a } 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源 {requesting url}。

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.

它在 Firefox 上正常工作,我不知道为什么它不适用于 google chrome。我还没有尝试过任何其他类型的浏览器。任何帮助将不胜感激,谢谢。

回答by Clevison Luiz

Install the cors-headers package with

安装 cors-headers 包

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 记得添加为列表中的第一个

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 = [
    'google.com',
    'hostname.example.com',
    'localhost:8000',
    '127.0.0.1:9000'
]

回答by zxt077

Check your request url first.I had this problem when use vue-resource .And then find i missing '/' at the end or url.

首先检查您的请求 url。我在使用 vue-resource 时遇到了这个问题。然后发现我在末尾或 url 中缺少“/”。

回答by Pay C.

Make sure use 127.0.0.1NOT localhostbecause when using localhostbrowser may look up an IPv6 address... or set up localhostto explicitly to 127.0.0.1at /etc/hosts

确保使用127.0.0.1NOTlocalhost因为在使用localhost浏览器时可能会查找 IPv6 地址...或localhost明确设置为127.0.0.1at/etc/hosts

回答by Joel Wigton

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 middlewareby setting the following headers on the response:

通过在响应中设置以下标头,我让它没有任何 CORS 中间件的Django 中工作:

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

StackOverflow 上的大多数答案似乎都提到了第一个,但没有提到第二个。我刚刚确认它们都是必需的。您需要根据您的框架或请求方法(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 everysite access. Once working, you can restrict it for your requesting site only to make sure you don't have any formatting typos.

ps 您可以尝试"*"代替"requesting_site.com"初始开发来使其正常工作,但这将是一个允许每个站点访问的安全漏洞。工作后,您可以将其限制为仅用于请求站点,以确保您没有任何格式错别字。

回答by O-9

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.

从我的 Angular 应用程序进行 GET 调用时,我正在与这个 CORS 问题作斗争。1-2 小时后查看此错误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...

原来我的网址无效。/在 URL 的末尾遗漏了一个。我实际上尝试了每个答案......

See also: Django CORS API from AngularJS

另请参阅:来自 AngularJS 的 Django CORS API

edit: After looking at the server log I can see that HTTP 301 was returned on every failed call. Django returning HTTP 301?

编辑:查看服务器日志后,我可以看到每次失败的调用都返回 HTTP 301。Django 返回 HTTP 301?

回答by Ramesh Ponnusamy

In settings.py

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

如果没有解决,您应该在请求服务器(http://example.com)中启用核心

回答by Pansul Bhatt

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 = Truein your code as well.

也许您需要看看如何调用中间件。如果它们的顺序不正确,它们可能会抛出此错误。似乎您的'django.middleware.security.SecurityMiddleware'需要被推到'corsheaders.middleware.CorsMiddleware'. 此外,看起来您可能还需要添加CORS_ALLOW_CREDENTIALS = True代码。

Hope this helps.

希望这可以帮助。

回答by cece

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.

是 chrome 浏览器的原因;您可以在 chrome 中安装 CORS Toggle 应用程序或将您的网络代码部署到 nginx 或 apache,然后使用 chrome。

回答by Ajay Aneja

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

您可以安装django-cors-headers应用程序,并在 settings.py 中放入'corsheaders'INSTALLED_APPS 和

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

in the starting of the MIDDLEWARE of the settings

在设置的 MIDDLEWARE 的开始

The README of the Github link explains the details

Github链接的README解释了细节