【问题标题】:Is it true that I cannot request an API from a different domain using ajax, or am I just doing it wrong? [duplicate]我不能使用 ajax 从不同的域请求 API 是真的,还是我做错了? [复制]
【发布时间】:2014-08-20 22:52:09
【问题描述】:

我在http://www.domain_a.com 上有一个网站,我需要向http://domain_b.com 上托管的 JSON API 发出请求。现在,当我尝试以下操作时:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
      $.getJSON({
        url: "http://domain_b.com/service_api/v1/find.json?name=abcd", 
        dataType: 'json',
        beforeSend: setHeader,
        success: function(data) {console.log (data)}  
      });

      function setHeader (xhr) {
        console.log (xhr);
        xhr.setRequestHeader("Authorization", "sdkfhberg83hr87234bf87r432");
        console.log (xhr);
      }
      });    
    </script>
  </head>
  <body>
  </body>
</html>

我在 firebug 控制台中收到此错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domain_b/service_api/v1/find.json?name=abcd. This can be fixed by moving the resource to the same domain or enabling CORS.

是我做错了什么,还是根本不允许(会让我感到惊讶)?

【问题讨论】:

  • 你要找的是CORS,跨域资源共享,需要在托管API的域上设置。
  • 不允许,除非提供 api 的服务器设置标头表明允许

标签: ajax cors


【解决方案1】:

跨域资源共享就是你想要的。基本上,出于安全原因,同源策略只允许在同一域上运行的脚本访问彼此的 DOM。因此,除非您调用的 API 不支持 - 即。具有以下响应标头 - "Access-Control-Allow-Origin", "*" ,不允许此调用。

对此并不完全确定 - 但请尝试使用 PHP proxy

另外,this 可能对您有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2011-06-04
    • 2013-06-03
    • 2012-03-09
    相关资源
    最近更新 更多