Access HTTP Response Headers

Access HTTP Response Headers – AngularJS

Learn to Access HTTP Response Headers In Your AngularJS $http Request

Having been playing around with Angular for over 2 years, I found myself recently – for the first time – needing to access HTTP response headers in the success callback of my Angular $http request.

Looking around I found very little documentation on this so I thought I would write a short article.

First let’s look at a typical $http request:

    .success(function(data, status, headers, config){

    .error(function(data, status, headers, config){

This is a GET request to the URL Your success callback will execute when a 2xx-3xx status code is returned and your error callback when a 4xx-5xx status code is returned.

Usually we are focusing on the data parameter of our success callback when writing our code but today lets talk about the headers parameter.

Headers Parameter

The first thing I found was that the headers parameter was a function, some simple console logging helped me figure this out but unfortunately all this did for me was make me more confused…

I experimented first with invoking it and found that I got an object returned:

{content-type : text/html}

This made a little more sense but as only one header was listed it was not the solutions I was looking for.

I found that passing in my header as a string into the headers() function returned its value but I was still only getting access to the content-type header.

Server Config

After some digging I found this bit of code to through in my Apache Config:

Access-Control-Expose-Headers: X-Foo, ..

And voila! Now I could access my header either by returing the entire object – headers()

    content-type : text/html,
    x-foo : "my stuff here"

Or by accessing it individually – headers(‘x-foo’)

I hope this was helpful to you and saves you the time it took me to figure this trivial problem out.

Pro Tip: Reference MDN

Personally I love to look for the MDN (Mozilla Developers Network) link on my Google results. They have great and accurate documentation. Here is an article on HTTP headers:

4 thoughts on “Access HTTP Response Headers – AngularJS

  1. Philip Snyder

    Thank you! I was having a hell of a time figuring out why my response headers weren’t available and worked like a charm!


Leave a Reply

Your email address will not be published. Required fields are marked *