AngularJS $http returns status code 0 from failed

2019-02-09 03:49发布

问题:

Okay, I've looked all over for this. Basically we're using $http request that ARE cross domain requests. Our server allows the domain and when a request returns 200, everything is OK. However, anytime our server returns an error, 500, 401, whatever, Angular thinks it's a CORS issue.

I debugged the response with Fiddler to verify my server IS returning a 500, yet Angular chokes on it.

Here's the request:

       var params = {
            url: "fakehost/example",
            method: 'GET',
            headers: {
                "Authorization": "Basic encodedAuthExample"
            }
        };

       $http(params).then(
            function (response) { // success 

            },
            function (error) { // error 
                 // error.status is always 0, never includes data error msg
            });

Then in the console, I will see this:

XMLHttpRequest cannot load fakehost/example. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mylocalhost:5750' is therefore not allowed access.

Yet, in fiddler, the true response is:

HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 26 Aug 2014 12:18:17 GMT
Content-Length: 5683

{"errorId":null,"errorMessage":"Index was outside the bounds of the array.","errorDescription":"Stack trace here"}

I'm on AngularJS v1.2.16

回答1:

I think I found an answer, looks like you will have to inject in your asp.net pipeline the correct CORS headers, as mentioned here.