调用带有AngularJS和ngResource外部APIAngularJS、ngResource、API

由网友(哀家不死伱終究是妃)分享简介:我们目前正在开发一个小AngularJS项目并从前端开始,所以纯HTML和JavaScript。we are currently developing a little AngularJS project and starting from the frontend, so pure HTML and JavaScr...

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

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

不过,我们需要用一些ngResource API调用。目前,我们正在使用罐头嘲笑JSON返回值。

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

之所以这样说,返回一个JSON:

Say this returns a JSON:

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

我希望能够从ngResource调用此

I want to be able to call this from ngResource:

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

由于某种原因,这并不工作,但端点是否正常工作。角只是让一个选项请求该URL。

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

这是某种形式的XSS防护魔法,如何解决呢?

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

更新:增加了IP地址示例

Update: Added the IP-Address to example

编辑:

我已经改变了模拟API服务器,这样CORS是允许的。

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

我现在回到这个头,并通过

I return now this header and the OPTIONS request goes through

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:*

但现在,get请求被取消(无响应被返回)。所以我想角做一些一种魔力。

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

推荐答案

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

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

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});
});

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

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

阅读全文

相关推荐

最新文章