[javascript] How to read response headers in angularjs?

My server returns this kind of header: Content-Range:0-10/0:

enter image description here

I tried to read this header in angular with no luck:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log(response.headers());
  return response.data;
});

which just prints

Object {content-type: "application/json; charset=utf-8"}

Any ideas how to access the content range header?

This question is related to javascript angularjs angular-http

The answer is


response.headers();

will give you all the headers (defaulat & customs). worked for me !!

enter image description here

enter image description here

Note . I tested on the same domain only. We may need to add Access-Control-Expose-Headers header on the server for cross domain.


The response headers in case of cors remain hidden. You need to add in response headers to direct the Angular to expose headers to javascript.

// From server response headers :
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, 
Content-Type, Accept, Authorization, X-Custom-header");
header("Access-Control-Expose-Headers: X-Custom-header");
header("X-Custom-header: $some data");

var data = res.headers.get('X-Custom-header');

Source : https://github.com/angular/angular/issues/5237


According the MDN custom headers are not exposed by default. The server admin need to expose them using "Access-Control-Expose-Headers" in the same fashion they deal with "access-control-allow-origin"

See this MDN link for confirmation [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers]


Why not simply try this:

var promise = $http.get(url, {
    params: query
}).then(function(response) {
  console.log('Content-Range: ' + response.headers('Content-Range'));
  return response.data;
});

Especially if you want to return the promise so it could be a part of a promises chain.


Updated based on Muhammad's answer...

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(headers()['Content-Range']);
  })
  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Additionally to Eugene Retunsky's answer, quoting from $http documentation regarding the response:

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.

Please note that the argument callback order for $resource (v1.6) is not the same as above:

Success callback is called with (value (Object|Array), responseHeaders (Function), status (number), statusText (string)) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angular-http

Angular 4.3 - HttpClient set params Angular 2 http post params and body How to read response headers in angularjs? AngularJs $http.post() does not send data Angularjs autocomplete from $http $http get parameters does not work Error handling in AngularJS http get then construct How to cancel an $http request in AngularJS? AngularJs ReferenceError: $http is not defined Processing $http response in service