AngularJS ignoring some headers

2019-05-11 02:58发布

问题:

I am playing a bit with angular and i came across a little problem.

I am trying to set a custom header for http response and later read its value on angular's side. The header is set and I am sure of that because chrome's debug tool confirms that:

That means server side is fine. So far so good.

The problems occurs when I try to access headers via http response interceptor in angular and display them in console. Here's the code in coffeescript:

angular.module('app').factory 'httpInterceptor', function($q) ->
  (promise) ->
    success = (response) ->
      console.log response.headers()
      response
    error = (response) ->
      $q.reject(response)

    promise.then success, error

angular.module('app').config ($httpProvider) ->
  $httpProvider.responseInterceptors.push('httpInterceptor')

And i get the output:

I really don't understand why does angular strip all those headers. Could anyone explain it to me? Is there any way to access my custom header's value?

Thank you in advance.

回答1:

I have found an answer to my own question. It's not Angular's fault. The thing is I am using CORS.

I have found such information in CORS documentation:

User agents must filter out all response headers other than those that are a simple response header or of which the field name is an ASCII case-insensitive match for one of the values of the Access-Control-Expose-Headers headers (if any), before exposing response headers to APIs defined in CORS API specifications.

The getResponseHeader() method of XMLHttpRequest will therefore not expose any header not indicated above.

It means that I have to simply add a header Access-Control-Expose-Headers: custom-header.