2013-04-08 25 views
24

Tôi có mã đơn giản:

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

Nó hoạt động tốt, nhưng hàm lỗi không bao giờ được gọi là, ngay cả khi tôi trả lại 404 (Not Found) từ máy chủ .. Trong trường hợp đó, hàm này gọi hàm 'thành công' với trạng thái = 404 ...

Điều đó có đúng không?

Cảm ơn

Fiddler:

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 

Trả lời

5

Vấn đề là máy chủ web của bạn, nó được thiết lập nội dung dài đến 0 có nghĩa là đó là một giá trị hợp lệ khi bạn có thể nhìn thấy trên HTTP/1.1 specification.

Ngoài ra tôi đã làm ví dụ về JSFiddle hiển thị các ví dụ về lỗi và thành công. Xem here.

Các tiêu đề từ ví dụ lỗi:

Yêu cầu:

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` 

đáp ứng:

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 
+3

Điều này là không chính xác. Angularjs không quan tâm đến độ dài của nội dung. – AgDude

+4

Câu trả lời này không nên được đánh dấu là đúng, nó thực sự sai như AgDude đã đề cập. Đối với tôi câu trả lời đúng là câu trả lời từ @wilver (xem bên dưới)! – Nabi

3

Nếu bạn đang sử dụng AngularJS phiên bản 1.1.1 hoặc cao hơn ...

Liệu phụ thêm việc '.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; 
}); 

Nếu có, nó cũng có thể được sửa với:

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

Xem này =>Angular JS Fails After Upgrade from 1.1.0 to 1.1.1

+0

Xin chào, phụ .json được tạo ra lỗi: { "message": "Không tìm thấy tài nguyên HTTP nào khớp với yêu cầu URI 'http: // localhost: 4021/api/test.json'.", "messageDetail": "Không tìm thấy loại nào khớp với bộ điều khiển có tên 'người dùng. json '. "} ... Tôi đang sử dụng .NET Web API trên máy chủ ... – Paul

+0

Tôi đã thêm yêu cầu/phản hồi của câu hỏi vào câu hỏi – Paul

+0

lý do tại sao sẽ thay đổi trợ giúp mở rộng trong trường hợp cụ thể này ... Tôi không thấy nó –

24

tôi đã cùng một vấn đề và, một cách trung thực, hãy làm theo các gợi ý của bài viết này đưa cho tôi theo hướng sai ... vì vậy, tôi chia sẻ trường hợp/giải pháp của tôi vì vậy khác trong tình huống tương tự của tôi có thể tiết kiệm thời gian.

Tôi đang sử dụng Angular.js 1.2.14 + WebAPI 2. này phản ứng của tôi cho một tình trạng 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==?= 

Như bạn thấy, Content-Chiều dài: 0, nhưng đó là ok.

Vấn đề của tôi là sử dụng uncorrect của Angular.js đánh chặn, đặc biệt là một cái gì đó như thế này:

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

trở về kết quả mà không cần ném một ngoại lệ hay từ chối những lời hứa (as written in docs) làm cho góc tin rằng tôi muốn chuyển đổi từ chối ở độ phân giải chính xác và sau đó gọi lại thành công.

tôi sửa mã của tôi như sau:

responseError: function (result) {      
       // check something 
       return $q.reject(result); 
      } 
0

Chúng tôi di chuyển bài viết tới một nhà máy, chúng tôi không thực sự quan tâm ở đây về thử nghiệm http thứ $, chỉ là những gì nó về thành công hay lỗi:

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

Chúng tôi gọi nó là như thế này:

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

Chúng tôi kiểm tra nó như thế này:

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

}); 
2

Có lẽ một chút về muộn nhưng ... Tại thời điểm góc yêu cầu $ http cung cấp cho bạn một tiền đề để bạn có thể thay đổi nó thành:

$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); 
}); 
Các vấn đề liên quan