How to read response headers with $resource?

All we need is an easy explanation of the problem, so here it is.

I’m using $resource to get data from my RESTful service and I need to read response headers to get ‘X-Page’ and ‘X-Total-Pages’ value for pagination.

Example:

Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:2637
Content-Type:application/json
Date:Thu, 10 Apr 2014 16:53:01 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
Vary:Origin
X-Page:1
X-Per-Page:10
X-Total:17
X-Total-Pages:2

But I couldn’t get full headers from server.

This is returned headers:
enter image description here

This is the headers from server:
enter image description here

This is my code:

.factory('TestAPI', ['$resource',
        function ($resource) {
            return $resource("http://ip.jsontest.com/?callback=showIP", {}, {
                query: {
                    method: 'GET'
                }
            });
        }])

TestAPI.query({}, function (value, responseHeaders) {
                console.log(responseHeaders());
            }, function (response) {
                console.log(response);
 });

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In your response headers you have to add the following header:

Access-Control-Expose-Headers: X-Total-Pages, X-Page

With this, the browser is capable to expose your customs headers an read it angular.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply