24

我有那个简单的代码:

$http.get("/api/test")
    .success(function (data, status, headers, config) {
        console.log(data);
        return data;
    }).error(function (data, status, headers, config) {
        alert("error");
        return status;
});

它工作正常,但永远不会调用错误函数,即使我从服务器返回 404(未找到)......在这种情况下,它调用状态 = 404 的“成功”函数......

那是对的吗?

谢谢

提琴手:

Request

GET http://localhost:41234/api/test HTTP/1.1
Host: localhost:41234
Connection: keep-alive
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko)    Chrome/25.0.1364.172 Safari/537.22
Referer: http://localhost:41234/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: ASP.NET_SessionId=bd1b3rib5j4beub0xbuhb1hm; FormsAuthentication=xxxxx

Response

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcUGVzc29hxvY2FyLkFwaVxhcGcg==?=
X-Powered-By: ASP.NET
Content-Length: 0
4

5 回答 5

29

我遇到了同样的问题,老实说,按照这篇文章的提示,我走错了方向……所以,我分享了我的案例/解决方案,这样在我同样情况下的其他人可以节省时间。

我正在使用 Angular.js 1.2.14 + WebApi 2。这是我对 NotFound 状态的响应:

Cache-Control:no-cache
Content-Length:0
Date:Sat, 15 Mar 2014 14:28:35 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcU3ZpbHVwcG9EaXNjaXR1clxhcGlcTWFnMTRcYXBpXGxlc3Nvblw4NA==?=

如您所见,Content-Lenght:0,但没关系。

我的问题是 Angular.js 拦截器的不正确使用,尤其是这样的:

responseError: function (result) {
                // check something 
                return result;
            }

返回结果而不抛出异常或拒绝承诺(如文档中所写)使 Angular 相信我想以正确的分辨率转换拒绝,然后调用成功回调。

我更正我的代码如下:

responseError: function (result) {                    
                // check something 
                return $q.reject(result);
            }
于 2014-03-15T15:00:08.053 回答
5

问题是您的网络服务器,它将 content-length 设置为 0,这意味着您可以在HTTP/1.1 规范中看到这是一个有效值。

我还在 JSFiddle 上做了一个示例,显示了错误和成功示例。见这里

错误示例中的标题:

要求:

GET /error/ HTTP/1.1
Host: fiddle.jshell.net
Connection: keep-alive
Accept: application/json, text/plain, */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like  Gecko) Chrome/26.0.1410.65 Safari/537.31
DNT: 1
Referer: http://fiddle.jshell.net/danielcsgomes/cAMc6/1/show/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: UTF-8,*;q=0.5
Cookie: csrftoken=4tNVNxC5v6BSq9yJCKkHlGFJBz3cClqd`

回复:

HTTP/1.1 404 NOT FOUND
Server: nginx/0.8.54
Date: Fri, 12 Apr 2013 00:38:07 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Cookie
Content-Encoding: gzip
于 2013-04-12T01:37:05.483 回答
3

如果您使用 AngularJS 1.1.1 或更高版本...

附加“.json”有效吗?:

$http.get("/api/test.json")
  .success(function (data, status, headers, config) {
      console.log(data);
      return data;
  }).error(function (data, status, headers, config) {
      alert("error");
      return status;
});

如果是这样,它也可以通过以下方式修复:

myModule.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}]);

看到这个 => Angular JS 在从 1.1.0 升级到 1.1.1 后失败

于 2013-04-08T20:35:04.040 回答
2

也许有点晚了,但是......目前 Angular $http 请求为您提供了一个前提,因此您可以将其更改为:

$http({
    method: "yourMethod",
    url: "yourUrl",
    data: {yourDataObj}
}).then(function (res) {     //first function "success"
    console.log(res.data);
}, function (err) {          //second function "error"
    console.log(err);
});
于 2016-03-21T11:54:42.173 回答
0

我们将帖子移至工厂,我们并不真正关心测试 $http 的东西,只关心它对成功或错误的作用:

factoryModule.factory('GiftFactory', function ($http, Settings) {
    var saveUrl = Settings.endpoints.saveUrl;

    return {
        createGift: function (data) {
            var gift = { gift: JSON.stringify(angular.toJson(data.gift)) };
            return $http.post(saveUrl, gift);
        }
    };
});

我们这样称呼它:

    $scope.submit = function () {
        $scope.submitting = true;
        GiftFactory.createGift($scope)
            .success(function () {
                $window.location = Giving.endpoints.indexUrl;
            }).error(function() {
                $scope.submitting = false;
                alert('an error occurred');
        });
    };

我们像这样测试它:

describe('donation controller', function () {
var $scope, q, window, controller;

beforeEach(module('giving.donation'));
beforeEach(inject(function ($controller, $rootScope, $q) {
    $scope = $rootScope.$new();
    window = {};
    q = $q;
    giftFactory = {};
    controller = $controller('DonationController', { $scope: $scope, $window: window, GiftFactory: giftFactory });
}));

describe('submit', function () {
    var deferred;
    beforeEach(function () {
        deferred = q.defer();

        deferred.promise.success = function (fn) {
            deferred.promise.then(
                function (response) {
                    fn(response.data, response.status, response.headers);
                });
            return deferred.promise;
        };
        deferred.promise.error = function (fn) {
            deferred.promise.then(null,
                function (response) {
                    fn(response.data, response.status, response.headers);
                });
            return deferred.promise;
        };
    });

    it('should redirect on success', function () {
        //Arrange
        Giving = { endpoints: { indexUrl: "/testurl" } };

        giftFactory.createGift = function () {
            return deferred.promise;
        };

        //Act
        $scope.submit();

        deferred.resolve({});
        $scope.$apply();

        //Assert
        expect($scope.submitting).toBeTruthy();
        expect(window.location).toBe('/testurl');
    });

    it('should set submitting back to false on error', function () {
        //Arrange
        Giving = { endpoints: { indexUrl: "/testurl" } };

        giftFactory.createGift = function () {
            return deferred.promise;
        };

        //Act
        $scope.submit();

        deferred.reject({});
        $scope.$apply();

        //Assert
        expect($scope.submitting).toBeFalsy();
        expect(window.location).toBeUndefined();
    });
});

});
于 2014-04-30T14:33:14.960 回答