Response header is present in browser but not parsed by Angular $http response.headers()

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

In our Angular app, we need to parse response headers of some $http.

In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35.

Opening the Network tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35 is present.

in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http.

Is there a way to access in $http the ‘raw’ response and write our custom parser for the header?

$http.({method: 'GET', url: apiUrl,)
    .then( function(response){
        console.log('headers: ', response.headers());
        console.log('results header: ', response.headers('X-Total-Results'));
        // ...

console output

headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}

results header: null

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

The reason you can’t read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header.

Your server needs to send this header:


To answer your question in the comments, The Access-Control-Allow-Headers does not allow wildcards according to the W3 Spec

Method 2

Use $httpProvider.interceptors you can intercept both the request as well as the response

for example

$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
             return {
                 'responseError': function (response) {
                 'response': function (response) {
                 'request': function (response) {

Update : You can retrive your headers info in call itself

$http.({method: 'GET', url: apiUrl)
    .then( (data, status, headers, config){
        console.log('headers: ', config.headers);
        console.log('results header: ', config.headers('X-Total-Results'));
        // ...

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

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

Leave a Reply