AngularJS:使用 ngResource 执行 GET 请求时的状态代码 0

AngularJS: Status code 0 when executing GET request using ngResource

本文关键字:状态 代码 请求 GET 使用 ngResource 执行 AngularJS      更新时间:2023-09-26

我是AngularJS的新手,所以请耐心等待。我得到了以下代码:

var testModule = angular.module("testModule", ['ngResource']);
testModule.config(function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://api.twitter.com/**']);
}); 
testModule.controller("SecondController",
    function SecondController($scope, $resource){
        $scope.secondField = "Hello World";
        try{
            var restClient = 
                //$resource("https://api.github.com/repos/angular/angular.js/issues", [],
                $resource("https://api.twitter.com/1.1/search/tweets.json", [],
                    {
                        "get":{method:"GET", headers:{"Accept":"application/json"},
                            interceptor: {
                                "response":function(data){
                                    alert("Response: " + data);
                                },
                                "responseError":function(data){
                                    alert("Error: " + data);
                                }
                            }
                        }
                    });
            $scope.about = restClient.get();
        } catch(err) {
            $scope.error = err.message;
        }
        $scope.done = true;
    }
);

它应该执行 responseError 函数,data.status 应该等于 215(请求需要身份验证才能成功通过(。相反,响应代码为 0。

实际上正在尝试访问不同的 API(不需要身份验证(,但状态代码也是 0,我真的不知道问题可能是什么。到目前为止,我唯一可以执行的成功请求是:

获取 https://api.github.com/repos/angular/angular.js/issues

由 $resource.query(( 执行。但是,无论是推特还是目标 API 都无法访问。我希望为我提供Twitter示例的解决方案可以帮助我解决我的问题。

谢谢。

编辑:使用AngularJS 1.2.0 rc2

这可能是因为跨域请求。当您尝试访问不同域的 Web 服务时,将出现状态代码 0。在这种情况下,您需要在ngResource中使用JSONP作为方法。

http://docs.angularjs.org/api/ngResource.$resource