【问题标题】:CORS django 'Access-Control-Allow-Origin'CORS django'访问控制允许来源'
【发布时间】:2016-06-02 00:11:16
【问题描述】:

我试图让 CORS 请求正常工作。使用以下 JS 代码,我收到此错误:XMLHttpRequest cannot load http://localhost:65491/?token=u80h9kil9kjuu02539buak4r6n&user=~me. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50303' is therefore not allowed access.

这是JS代码:

$.ajax({
     url: "http://localhost:60906/",
     data: {token : 'u80h9kil9kjuu02539buak4r6n', user : '~me'},
     type: "GET",
     crossDomain: true,
     success: function( response ) {
         alert('Success!' + response);
         var context = response;
        }
  });

当我使用 chrome 的 devtools 查看网络时,我发现确实没有 'Access-Control-Allow-Origin' 标头。但是当我手动加载网站时,它就存在了!

我使用以下代码设置标题:

response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response

希望得到帮助!

【问题讨论】:

  • 能否请您显示更多您的观点的代码?
  • 您是否尝试将 crossDomain 设置为 true?默认为假。
  • @gaemaf 这行得通,但现在我得到了:Failed to load resource: net::ERR_CONNECTION_REFUSED 我使用了一个干净的 Chrome 版本(就像我在测试代码时经常做的那样),所以没有导致问题的广告拦截器。 没关系,网址中的拼写错误,它仍然不起作用!我现在确实遇到了另一个错误。我现在正在编辑问题。

标签: jquery ajax django cors django-cors-headers


【解决方案1】:

上面写着No 'Access-Control-Allow-Origin' header is present on the requested resource.,这意味着您的服务器应用程序需要调整才能接受跨源请求。 由于安全原因,跨源请求默认情况下不起作用。您需要启用它们。

对于 django,有一个维护包,其中包含大量设置:https://github.com/ottoyiu/django-cors-headers/

【讨论】:

  • 我使用了 django-cors-headers,当请求主机是 'localhost' 和 '127.0.0.1' 时,它不起作用,没有 'Access-Control-Allow-Origin' 标头。主机是我的ip,很好用。
  • @YETI,按照 T.Opletal 给出的链接中的说明尝试CORS_ORIGIN_ALLOW_ALL = True
  • 这非常重要,除非您允许 CORS,否则您无法对响应执行任何操作。你甚至不能循环并打印出来!谢谢一堆 T. Opletal
【解决方案2】:

经过 2 小时的故障排除后,我找到了解决方案:TYPO in url。 检查两次,也许它也能解决你的问题。

【讨论】:

    【解决方案3】:

    要使这件事起作用,您需要做两件事:


    • 只需在 settings.py

    • CORS_ORIGIN_WHITELIST 中输入 http:// 而不是 https://
    • 在同一个文件中添加CORS_ORIGIN_ALLOW = True

    【讨论】:

    • 如果设置 CORS_ORIGIN_ALLOW = True 那么 CORS_ORIGIN_WHITELIST 没有任何意义,
    猜你喜欢
    • 2021-09-07
    • 2017-12-28
    • 2019-02-09
    • 2016-06-27
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2020-11-26
    相关资源
    最近更新 更多