keldar
keldar

Reputation: 6252

$.ajax works, $http does not (status 0; CORS?)

I have a cloud service I am attempting to download data from. I can use jQuery's $.ajax function to obtain this data with no issue - all status codes expected are returned.

AngularJS is a different story and I have no idea why. I am using the $http service to get(...) my data. I know there are a few errors the $http is likely to fail on (a 404 if the user mistypes something in the registration box, or a 403 if they are not authenticated).

Yet, no matter what I attempt - I receive a status: 0 response everytime and this is pretty useless as you can imagine.

I have a basic function as follows:

function get(config) {
    $ionicLoading.show();

    return $http(config)
        .then(function (data) {
            console.log(data);
            return data.data;
        },
        function (data) {
            console.log(data);
            throw 'Connection error';
        })
        .finally(function () {
            $ionicLoading.hide();
        }
    );
}

I use this to test the connection of one of my cloud services.

Which is fine; however - if I pass it an incorrect subdomain for my service, e.g. incorrect.myservice.com - I receive the following error:

GET https://incorrect.myservice.com/ net::ERR_NAME_NOT_RESOLVED

Which is good - that should result in a 404 error(?).

But, the data returned in the error callback is:

Object {data: "", status: 0, headers: function, config: Object, statusText: ""}

Which is bad - it should not be 0? It should be 404. I done some research, and it appears that CORS is a bit of a headache in AngularJS $http.

However, from what I have read - it appears that CORS is enabled on my server because looking at the response in Fiddler/Chrome/IE etc., all responses are returning the Access-Control-Allow-Headers: * and Access-Control-Allow-Headers: * which is what is required for CORS.

response header

So I am completely lost on how to further debug this, as I require this functionality in my application. But $http does not appear to be behaving how it should be?

Please can somebody assist and provide a pointer.

All error codes are returning with status: 0 and I have no idea why?

Upvotes: 1

Views: 592

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146124

GET https://incorrect.myservice.com/ net::ERR_NAME_NOT_RESOLVED Which is good - that should result in a 404 error(?).

Nope. If you can't resolve the host name to an IP address, you can't make a TCP connection to it, so you can't even send the HTTP GET, and if you can't send the request, you can't get the response, which is where the 404 would come from. This is a lower level networking error and you don't even get to do any HTTP, so you get no HTTP status code.

This is also not a CORS error. The browser (at least Chrome) will print a really clear and explicit error message if anything goes wrong with CORS.

Upvotes: 3

Related Questions