javascript 使用 AngularJS 和 ngResource 调用外部 api

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17108078/
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-10-27 07:07:33  来源:igfitidea点击:

calling external api with AngularJS and ngResource

javascriptangularjs

提问by leifg

we are currently developing a little AngularJS project and starting from the frontend, so pure HTML and JavaScript.

我们目前正在开发一个小 AngularJS 项目并从前端开始,所以纯 HTML 和 JavaScript。

However, we need to make some API calls using ngResource. At the moment we are using cannedto mock the json return value.

但是,我们需要使用 ngResource 进行一些 API 调用。目前我们正在使用canned来模拟 json 返回值。

Say this returns a JSON:

假设这将返回一个 JSON:

GET http://ip-address/something/1.json

I want to be able to call this from ngResource:

我希望能够从 ngResource 调用它:

app.controller('SomethingCtrl', function ($scope, $resource) {
  Something = $resource("http://ip-address/something/:id", {id: "@id"});
  $scope.something = Something.get({id:1});
});

For some reason this does not work, although the endpoint is working correctly. Angular just makes an option request to this URL.

出于某种原因,这不起作用,尽管端点工作正常。Angular 只是向这个 URL 发出一个选项请求。

Is this some kind of XSS protection magic and how do I solve it?

这是某种 XSS 保护魔法,我该如何解决?

Update: Added the IP-Address to example

更新:在示例中添加了 IP 地址

EDIT:

编辑:

I have changed the mock API server, so that CORS is allowed.

我已经更改了模拟 API 服务器,因此允许使用 CORS。

I return now this header and the OPTIONS request goes through

我现在返回这个标题并且 OPTIONS 请求通过

Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Max-Age:86400
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin:*

But now, the get request gets cancelled (no response gets returned). So I suppose Angular does some kind of magic.

但是现在,get 请求被取消(没有响应被返回)。所以我认为 Angular 有某种魔力。

回答by leifg

Ok I figured it out. You need to inject the $http service and set the useXDomainflag.

好吧,我想通了。您需要注入 $http 服务并设置useXDomain标志。

app.controller('SomethingCtrl', function ($scope, $http, $resource) {
  $http.defaults.useXDomain = true;
  Something = $resource("http://ip-address/something/:id", {id: "@id"});
  $scope.something = Something.get({id:1});
});

Furthermore. Every request to the service must return the correct CORS headers (not only the OPTIONS request)

此外。对服务的每个请求都必须返回正确的 CORS 标头(不仅是 OPTIONS 请求)