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 (Not Found) が返された場合でも、エラー関数が呼び出されることはありません...その場合、ステータス = 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;
            }

例外をスローしたり、約束を拒否したりせずに結果を返すと(docs に書かれているように)、Angularは拒否を正しい解決に変換したいと信じ、その後、成功のコールバックが呼び出されます。

次のようにコードを修正します。

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

問題は Web サーバーです。コンテンツの長さを 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 に答える
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 に答える