如何从 Angular 请求中检索 JSON 数据以访问另一个域的资源?

How to retrieve JSON data from Angular request to access another domain's resources?

我有一个奇怪的问题已经解决了几天。 问题与 Cross-Origin 资源共享 (CORS) 有关,我正在发出 Angular GET 请求并能够在 Firefox/Chrome 的开发人员工具中看到 JSON 收到响应 body,但是 Java 脚本(或浏览器或服务器)拒绝将响应交给我 body。 这是我的要求:

$http = angular.injector(["ng"]).get("$http"); //angular http object
 $http = angular.injector(["ng"]).get("$http"); 
    $http({
      method: 'GET',
      url: 'api.example.com/myPath',
      headers: {
        'Content-Type': 'application/json',

      }
    }).then(function successCallback(response) {
  
      alert("succeed: db "+JSON.stringify(response)); //this is not called
    

    }, function errorCallback(response) {
      alert("failed: " + JSON.stringify(response));//this is called
    });

如评论中所述,失败函数被调用而不是成功。 我可以 mention/post 我去过的 Stack-overflow 和其他链接,但是有大约 50 个,所以这里是其中的一些:

  1. SO 1
  2. SO 2
  3. SO 5
  4. Reddit 1
  5. GitHub 1

Headers 我试过了(除了代码中显示的内容):

"headers": {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Origin': '*'
      }


"headers": {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Origin': '*'
      }

"headers": {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Origin': '*'
      }


"headers": {
        'Accept': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Origin': '*'
      }


"headers": {
        'Accept': 'application/json',
        'Access-Control-Allow-Origin': '*'
      }

尝试了以上所有方法,其中一些不会收到 JSON 响应,而是发送 OPTIONS 请求并停止。

这是 Firefox 输出的样子:

Network

Console

这里是 Alert 函数的输出:

failed: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api.example.com/myPath","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"error"}

我尝试过的其他事情: 为 Chrome 安装名为 CORS 的插件:Was not effective at all, no difference

注意端点服务器不是NodeJS,它是Java,我在网上遇到的大多数答案都建议添加这些headers 在服务器,但是我的同事坚持 这个问题可以使用front-end Angular 来解决(特别是在他们看到正确响应 body Json 信息实际上来自服务器,如附图所示)

如果您使用的是 Angularjs 版本 >= 1.4 ,请这样做(注意要点)

$http({
  method: 'GET',
  url: 'api.example.com/myPath',
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'
  }
}).then(function(response) {
  alert("succeed: db "+JSON.stringify(response)); //this is not called

}).catch(function(response) {
  alert("failed: " + JSON.stringify(response));//this is called
});

试试这个

$http.get('api.example.com/myPath').then(
  function(res){ 
    alert('success')
    },
   function(err){
     alert(err)
  })

事实证明,只有 front-end 没有修复,浏览器仅在 Java 端点添加响应后才将 JSON 响应数据还给我 headers,在 NodeJS 中,我在添加以下内容之前可以正常工作:

 request(options, function(err, response, body) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.json(response);
  })

我不确定 Java 中是如何完成的,但这基本上就是他们所做的,只是将这些东西添加到 Java Web-service 中。 这就像 Java 服务器(尽管向浏览器发送 JSON 响应)告诉浏览器 ("Do not hand him the data because I do not have such instructions on my end")。我想这有点滑稽,但事实就是如此。