How do I get the HTTP response status code in AngularJS 1.2
Asked Answered
M

8

26

Using ngResource in AngularJS 1.2rc(x), how do I get the status code now?

RestAPI.save({resource}, {data}, function( response, responseHeaders ) {
});

where RestAPI is my ngResource.

The response has the $promise object and the resource returned from the server but not a status anymore. The responseHeaders() function only has a status if the server injects the status code into the header object, but not the true returned status code. So some servers may serve it and some might not.

Milliard answered 10/9, 2013 at 22:7 Comment(3)
Looks like similar: #17418033Gastineau
not similar at all. Its similar in the sense that both questions are asking about AngularJS and using ngResource but other than that completely different. I can get the response data just fine through response. What I can't get is the HTTP response status code in 1.2rc(x), which is a breaking change.Milliard
refer to this https://mcmap.net/q/536902/-how-can-i-get-status-code-using-resourceTeeter
S
13

You can use the promiss callbacks then, catch and finally after the $resource call.

For example. If you want to catch an error after a call, you would do something like this:

RestAPI.save({resource}, {data}, callbackFunction).$promise.catch(function(response) {
    //this will be fired upon error
    if(response.status == 500) alert('Something baaad happend');
}).then(function() {
    //this will be fired upon success
});

The response object will have status and the statusText properties. status being an integer status code and statusText the text. You'll also have the data property containing the server response.

edit: as suggested, it was response.status

Spiller answered 16/7, 2014 at 22:31 Comment(2)
I return a 400 from my WebAPI and that still doesn't trigger the catch. The "then" doesn't have response in it.Wellordered
Not true my responses do not have the statusMalagasy
R
12

You must add an interceptor inside your resource declaration. Like this:

var resource = $resource(url, {}, {
    get: {
        method: 'GET'
        interceptor: {
            response: function(response) {      
                var result = response.resource;        
                result.$status = response.status;
                return result;
            }
        }
    }                            
});

Usage:

resource.get(params, function(result) {
    console.log(result.$status)
});

IMO status code should have been provided by default. There is an issue for this https://github.com/angular/angular.js/issues/8341

Rayburn answered 3/4, 2015 at 16:25 Comment(5)
This does not work if connection is not successful. If you have a 404 error it will not show it.Bushey
@MarioShtika this is an old answer. Have you tried https://mcmap.net/q/520126/-how-do-i-get-the-http-response-status-code-in-angularjs-1-2 ?Rayburn
@MarioShtika as far as I can remember there was an error callback as well. In your case the 404 error should be handled in there. It was a long time ago and I don't program with angular anymore.Rayburn
I believe that the answer is a combination of both, because in the Bardiels's answer it doesn't show the status when the connection is successfullBushey
@MarioShtika yeah probablyRayburn
L
4

For anyone using a newer version of Angular, looks like we've had access to the status code as a 3rd param to the transformResponse function since angular 1.3, but it was never documented properly in the $resource docs.

Libbielibbna answered 10/2, 2016 at 1:12 Comment(0)
I
3

I agreed responseHeaders() function will only return response's header,but you can custom it and it's useful anyway.

1.

To solve you problem. With the following:($$service is my $resource instance.)

var serve = new $$service();
serve.id = "hello_wrongPath"; // wrong path,will return 404
serve.$get()
    .then(function (data) {
        console.log("~~~hi~~~");
        console.log(data);
        return data;
    })
    .catch(function (error) {
        console.log("~~~error~~~");
        console.log(error);
        console.log(error.status); // --> 404
        console.log(error.statusText); // --> "Not Found"
        console.log(error.config.timeout); // --> 5000
        console.log(error.config.method); // --> GET
        console.log(error.config.url); // --> request url
        console.log(error.headers("content-type"));// --> "text/plain"
        return error.$promise;
    })
    .finally(function(data){
        console.log("~~~finally~~~");
        console.log(data); // --> undefined
    });

In this way,u can only catch status,statusText,timeout,method,headers(same with responseHeaders) in ERROR response.

2.

If you want to see response details in success response,I used a interceptor like this:

ng.module("baseInterceptor", [])
    .factory("baseInterceptor", ["$q", function ($q) {
        return {
            'request': function (config) {
                console.info(config);
                //set timeout for all request
                config.timeout = 5000;
                return config;
            },
            'requestError': function (rejection) {
                console.info(rejection);
                return $q.reject(rejection);
            },
            'response': function (response) {
                console.log("~~interceptor response success~~");
                console.log(response);
                console.log(response.status);
                console.log(response.config.url);
                return response;
            },
            'responseError': function (rejection) {
                console.log("~~interceptor response error~~");
                console.log(rejection);
                console.log(rejection.status);
                return $q.reject(rejection);
            }
        };
    }]);

and then add interceptor to module:

.config(["$httpProvider", function ($httpProvider) {
    $httpProvider.interceptors.push("baseInterceptor");
}])
Ideogram answered 10/11, 2014 at 6:4 Comment(0)
S
3

You can get response status like this:

$http.get(url).then(function(response){
  console.log(response.status); //successful status like OK
}, function(response){
  console.log(response.status); //error status like 400-Bad Request
})
Sabadilla answered 28/6, 2017 at 11:26 Comment(0)
B
0

I think the right answer is a combination of Bardiel's and Ara's answers.

After adding an interceptor inside your resource declaration. Like this:

var resource = $resource(url, {}, {
    get: {
        method: 'GET'
        interceptor: {
            response: function(response) {      
                var result = response.resource;        
                result.$status = response.status;
                return result;
            }
        }
    }                            
});

Use it as below:

RestAPI.save()
.query(function(response) {
    // This will return status code from API like 200, 201 etc
    console.log(response.$status);
})
.$promise.catch(function(response) {
    // This will return status code from server side like 404, 500 etc
    console.log(response.status);
});
Bushey answered 8/12, 2015 at 10:14 Comment(0)
H
0

I'm using AngularJS v1.5.6, and I do it like this (in my case I put the "getData" method inside a service):

function getData(url) {
    return $q(function (resolve, reject) {
        $http.get(url).then(success, error);

        function success(response) {
            resolve(response);
        }
        function error(err) {
            reject(err);
        }
    });
}

then in the controller (for example), call that like this:

function sendGetRequest() {
    var promise = service.getData("someUrlGetService");
    promise.then(function(response) {
        //do something with the response data
        console.log(response.data);
    }, function(response) {
        //do something with the error
        console.log('Error status: ' + response.status);
    });
}

As documentation says, the response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

See https://docs.angularjs.org/api/ng/service/$http

Hope it helps!

Hitchhike answered 29/8, 2016 at 17:3 Comment(0)
T
-1

I had faced the similar problem.I looked into the angular lib and added a few lines to have status returned in the response itself.In this file,find where promise is being returned.

Replace code block starting with

var promise = $http(httpConfig).then(function(response)

with the following

var promise = $http(httpConfig).then(function(response) {
            var data = response.data,
                promise = value.$promise;

            if (data) {
              // Need to convert action.isArray to boolean in case it is undefined
              // jshint -W018
              if ( angular.isArray(data) !== (!!action.isArray) ) {
                throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' +
                  'response to contain an {0} but got an {1}',
                  action.isArray?'array':'object', angular.isArray(data)?'array':'object');
              }
              // jshint +W018
              if (action.isArray) {
                value.length = 0;
                forEach(data, function(item) {
                  value.push(new Resource(item));
                });
              } else {
                copy(data, value);
                value.$promise = promise;
              }
            }

            value.status = response.status;
            value.$resolved = true;

            response.resource = value;

            return response;
          }, function(response) {
            value.status = response.status;
            value.$resolved = true;

            (error||noop)(response);

            return $q.reject(response);
          });

or you can add this line

value.status = response.status;

and then access status in code like reponse.status.Though,this is kind of hack but worked for me.I also had to make changes in the minified version.

Timoshenko answered 2/12, 2013 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.