简体   繁体   English

django 中的“请求的资源上不存在‘Access-Control-Allow-Origin’header”

[英]"No 'Access-Control-Allow-Origin' header is present on the requested resource" in django

I am newbie to django and using it as back end for an application that creates users.我是 django 的新手,并将其用作创建用户的应用程序的后端。 In front end the code for posting the user name is:在前端发布用户名的代码是:

var xobj = new XMLHttpRequest();
              xobj.overrideMimeType("application/json");
              xobj.open('POST', "http://www.local:8000/create_user/", true);
                xobj.setRequestHeader("Access-Control-Allow-Origin", "*");
              xobj.onreadystatechange = function () {
                  if (xobj.readyState == 4 && xobj.status == "200") {
                      console.log(xobj.responseText);
                  }
            }
              xobj.send(json);    

On back end the function associated with url handles json but i am getting the error "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://www.local:54521 ' is therefore not allowed access".在后端,与 url 关联的 function 处理 json,但我收到错误“请求的资源上不存在‘Access-Control-Allow- Origin’header。Origin‘http://www.local:54521 ’因此不是允许访问”。 What is the solution for this problem?这个问题的解决方案是什么? Also I have followed the steps from " https://gist.github.com/strogonoff/1369619 ", but problem persists.我也按照“ https://gist.github.com/strogonoff/1369619 ”中的步骤操作,但问题仍然存在。

Here's what I did when I got the same error from Django Rest Framework while sending an API request from Restangular.这是我在从 Django Rest Framework 发送 API 请求时遇到相同错误时所做的。 What this does is add CORS (Cross-Origin Resource Sharing) headers to responses from Django Rest Framework.这样做是将 CORS(跨源资源共享)标头添加到来自 Django Rest Framework 的响应中。 Not having CORS headers was the cause of the error.没有 CORS 标头是导致错误的原因。

In the Django Project root folder (where the manage.py file is located), do:在 Django 项目根文件夹(manage.py 文件所在的位置)中,执行以下操作:

pip install django-cors-headers

I tried it using virtualenv but was not able to get it to work, so I installed it without switching to virtualenv and got it installed.我使用 virtualenv 尝试了它,但无法让它工作,所以我没有切换到 virtualenv 就安装了它并安装了它。

After installing it, you have to make some edits to your django settings.py安装后,您必须对 django settings.py 进行一些编辑

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

CORS_ORIGIN_ALLOW_ALL = True   

Setting above to true allows all origins to be accepted.将上面设置为 true 允许接受所有来源。

References: https://github.com/ottoyiu/django-cors-headers参考资料: https : //github.com/ottoyiu/django-cors-headers

In my case, I had simply forgotten to add a trailing slash at the end of the REST API URL.就我而言,我只是忘记在 REST API URL 的末尾添加一个斜杠。 ie, I had this:即,我有这个:

http://127.0.0.1:8000/rest-auth/login

Instead of this:取而代之的是:

http://127.0.0.1:8000/rest-auth/login/

Your front and back end are on different ports which means your ajax requests are subject to cross origin security.您的前端和后端位于不同的端口上,这意味着您的 ajax 请求受到跨源安全性的约束。

You need to set up the back end to accept requests from different origins (or just different port numbers).您需要设置后端以接受来自不同来源(或只是不同端口号)的请求。

Try reading up on CORS and more specifically looking at django cors headers尝试阅读CORS ,更具体地查看django cors 标头

If django-cors-headers not resolved the problem try manual add Access-Control-Allow-Origin like this:如果django-cors-headers没有解决问题,请尝试手动添加Access-Control-Allow-Origin如下所示:

@api_view(['GET'])
def swanger(request):
  resutl = {'a': 1}
  resp = JsonResponse(resutl)
  resp['Access-Control-Allow-Origin'] = '*'
  return resp  

If using django for backend, you need to do the following 6 things:如果后端使用django,需要做以下6件事:

  • ensure you are in the virtualenv, then 'pip install django-cors-headers'确保您在 virtualenv 中,然后“pip install django-cors-headers”

  • add the following in your INSTALLED-APPS section of the settings.py: 'corsheaders',在 settings.py 的 INSTALLED-APPS 部分添加以下内容:'corsheaders',

  • add the following in the MIDDLEWARE section of the settings.py: 'corsheaders.middleware.CorsMiddleware' ,在 settings.py 的 MIDDLEWARE 部分添加以下内容: 'corsheaders.middleware.CorsMiddleware'
    'django.middleware.common.CommonMiddleware' , 'django.middleware.common.CommonMiddleware' ,

  • add either of the following at the bottom of the settings.py:在 settings.py 的底部添加以下任一内容:
    CORS_ORIGIN_ALLOW_ALL = True or CORS_ORIGIN_ALLOW_ALL = True

    CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000' ]
  • When using CORS_ORIGIN_WHITELIST, use the URL of the front end app where the GET Or POST request is coming from.使用 CORS_ORIGIN_WHITELIST 时,请使用 GET 或 POST 请求来自的前端应用程序的 URL。

  • Another gotcha is ensuring the URL pointing to django ends with a trailing slash.另一个问题是确保指向 django 的 URL 以斜杠结尾。

I faced the same issue.我遇到了同样的问题。

user3785412 's answer will work. user3785412的答案会起作用。 but, first time it may not work directly because of browser cache .但是,由于浏览器缓存,第一次它可能无法直接工作。 either try in another browser or clear cache before loosing hope.在失去希望之前尝试在另一个浏览器中清除缓存

I had API server in Django 2 hosted on Heroku and Angular 7 Client on Firebase.我在Django 2 中的API 服务器托管在 Heroku 和 Firebase 上的Angular 7客户端上。 I made all changes in settings.py as per user3785412 and still it would not work, wasted almost 3 hours.我根据 user3785412 在 settings.py 中进行了所有更改,但仍然无法正常工作,浪费了近 3 个小时。 Then came across on post which suggested cache could be issue .然后在帖子上遇到建议缓存可能是问题 opened in chrome and voila !在 chrome 中打开,

Hope this helps!希望这可以帮助! (My first answer here, please go easy) (我的第一个答案在这里,请放轻松)

I have observed this error in 3 scenarios:我在 3 种情况下观察到此错误:

  1. When the URL didn't end with / .当 URL 不以/结尾时。
  2. When URL had slashes like // or /// .当 URL 有像/////这样的斜杠时。
  3. When my server was not working.当我的服务器不工作时。 But after switching it on it worked fine.但是开机后效果很好。

在我的情况下,它是 localhost:8000 而 127.0.0.1 预期......在我的浏览器中将 localhost 更改为 127.0.0.1 就可以了

Add following line in middleware classes在中间件类中添加以下行

'corsheaders.middleware.CorsPostCsrfMiddleware'

so overall implementation would be:所以整体实施将是:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware'

    ...
)

CORS_ORIGIN_ALLOW_ALL = True   

check documentaion below for more info查看下面的文档以获取更多信息

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:通过在响应中设置以下标头,我让它没有任何 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 . StackOverflow 上的大多数答案似乎都提到了第一个,但没有提到第二个 I've just confirmed they are all required.我刚刚确认它们都是必需的。 You'll want to modify as needed for your framework or request method (GET, POST, OPTION).您需要根据您的框架或请求方法(GET、POST、OPTION)的需要进行修改。

ps 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. ps 您可以尝试使用"*"而不是"requesting_site.com"进行初始开发以使其正常工作,但这将是一个允许每个站点访问的安全漏洞。 Once working, you can restrict it for your requesting site only to make sure you don't have any formatting typos.工作后,您可以将其限制为仅用于请求站点,以确保您没有任何格式错别字。

i was using python 2.7 and due to some reasons i cannot change the python version to version 3 and it took me 3 hours to find a solution which is :我使用的是 python 2.7,由于某些原因,我无法将 python 版本更改为版本 3,我花了 3 个小时才找到解决方案:

response =  HttpResponse(json.dumps(result), content_type="application/json")
response["Access-Control-Allow-Origin"] = '*'
response["Access-Control-Allow-Methods"] = 'GET,PUT, OPTIONS'
response["Access-Control-Max-Age"] = '1000'
response["Access-Control-Allow-Headers"] = 'X-Requested-With, Content-Type'
return response

Add redirect: 'follow' to the headers on the client添加redirect: 'follow'到客户端的标题

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://www.example.com/auth/token/login/", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

I try the above answers with favs but all not work.我用 favs 尝试了上述答案,但都不起作用。 When I read again the terminal prompts and I found a warning: MIDDLEWARE_CLASSES is not compatible to the debug environment, use MIDDLEWARE .当我再次阅读终端提示时,我发现了一个警告: MIDDLEWARE_CLASSES is not compatible to the debug environment, use MIDDLEWARE I found the MIDDLEWARE settings and add 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', to it and it worked.我找到了 MIDDLEWARE 设置并向其中添加'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware',并且它起作用了。

Sigh

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 - No 'Access-Control-Allow-Origin' header is present on the requested resource. 请求的资源 Django 和 ReactJS 上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource Django and ReactJS Django 向浏览器发送响应它收到此错误:No 'Access-Control-Allow-Origin' header is present on the requested resource - Django sends it response to browser it gets this error: No 'Access-Control-Allow-Origin' header is present on the requested resource django-cors-headers 不工作:请求的资源上不存在“Access-Control-Allow-Origin”header - django-cors-headers not working: No 'Access-Control-Allow-Origin' header is present on the requested resource Django Python rest 框架,在 chrome 中请求的资源上没有 'Access-Control-Allow-Origin' header,在 firefox 中工作 - Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox 请求的资源上不存在“Access-Control-Allow-Origin”标头 React Django 错误 - No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error 在提取API django中请求的资源错误中不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource error in fetch API django Django digitalocean Spaces 请求的资源上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource with Django digitalocean Spaces 在 React 错误中调用 Django Api 时,请求的资源上不存在“Access-Control-Allow-Origin”标头 - While Calling Django Api On React Error is No 'Access-Control-Allow-Origin' header is present on the requested resource Django 中请求的资源上没有“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header on the requested resource in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM