angular: Http response do not include headers

Maybe i am doing something wrong but when i make a request with Http i can see on the Network tab on chrome that the response include a custom header called ‘Authorization’ used to refresh the JWT. But when i try to access the response.headers it prints empty on the console.

return this.http.request(req).map((res: Response) => console.log(res.headers.values()));

image

the same behaviour when printing keys().

the request headers, on the other hand, do print all the custom headers i add to the request.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 7
  • Comments: 53 (10 by maintainers)

Commits related to this issue

Most upvoted comments

@robwormald Adding ‘access-control-expose-headers’ : ‘x-total-count’ on the API solves it 😃

Thank you, tbragaf

Maybe it can help. My solution was to add this in the backend, the Access-Control-Expose-Headers made the trick:

...
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");

Then on front end this worked fine:

this._http.get(url, options).toPromise()
            .then(res => {
                var data = res.headers.get('X-Custom-header');
                console.log(data);
                return res;
            })

@pkozlowski-opensource Exactly, this is not an Angular issue. Is an API problem. With the header 'access-control-expose-headers' : 'name-of-expose-header' works fine.

The problem is that this doesn’t work with the header 'access-control-expose-headers' : '*'. You can’t use * and you have to put explicity the name of the headers that you want to expose.

@tbragaf I am having similar result as @ashokshetty1970 . Symptom:

  1. Using postman rest client do the request, all headers show just fine!
  2. Using angular 2 http, ONLY one header entry shows: “Content-Type” “application/json; charset=utf-8”

Hi all!

My custom headers are not being retrieved, for they do not appear it the headers map…

Anyone with the same problem?

tbragaf

@robwormald Make sure you test this under the limit of 24 hours 😃 http://plnkr.co/edit/V6RkITHxtwOLiwWJlezI?p=preview

The result should be x-total-count: 42

That header is not present, but you can see it if you go to the “Network” tab.

@robwormald If you confirm this, can you please re-open the issue?

Hello I have the same issue with angular2-rc.1:

I can ‘see’ the headers in the ‘network tab’ of the Chromium browser, but if I do a console.log(response.headers) I don’t see the same headers.

RESPONSE HEADERS FROM 'NETWORK TAB' OF CHROMIUM BROWSER:

Access-Control-Allow-Headers:Authorization, Content-Type, Accept, Cache-Control
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:*
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Fri, 13 May 2016 13:53:27 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
console.log(response.headers)

Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Expires:0
Pragma:no-cache

Thanks

Hey guys, i have found where the problem is and changed to get what i need.

In Http.dev.js on line 10645 aprox. i have added this basic snipet:

var arrayOfLines = _xhr.getAllResponseHeaders().match(/[^\r\n]+/g);
          var headers = new headers_1.Headers();
          for(var i = 0; i < arrayOfLines.length; i++){
            var line = arrayOfLines[i];
            var name = line.substr(0,line.indexOf(':')).trim();
            var val = line.substr(line.indexOf(':')+1).trim();

            headers.append(name,val);
          }

          responseOptions.headers = headers;

sorry i did not do it in typescript because i was lazy to recompile.

also, of course, had to add the headers to the dependencies array and required it. I hope it helps.

EDIT As the release 2.0.0-alpha.46 came out, the location changed. Still at the XHRConnection but the Http.dev.js has changed and now it is at line 721.

In xhr_backend.ts, XHRConnection class line 18.

Thanks

Can anyone explain why this header is necessary? If I can see it in my browser, then its already exposed, so why can’t angular2 or rx.js see it?

@tbragaf 👍 It works now without using ‘*’. In my case, I am using sails framework and I added exposeHeaders: 'what-ever-header' in cors.js file and the sails version has to be 0.12 and above.

In case there still is someone having trouble with this, I’ll leave my solution for both the backend and frontend.

Heres how you set the headers: https://github.com/rsbrum/NodeJS-RESTAPI-JWTAuth/blob/master/jwt-auth.js

Heres how you access the header on the client side: https://github.com/rsbrum/Angular6-JWT-Auth/blob/master/src/app/shared/interceptor/interceptor.service.ts

Hi.

Fixed by adding below code in webapi controller. returnValue.Content.Headers.Add(“x-filename”, “File.doc”); returnValue.Content.Headers.Add(“access-control-expose-headers”, new[] { “x-filename” });

Hi all, I’m having this same issue in alpha.44. I can’t access the response header information that are supposed to be present in the headers map of the response. Example:

var req = new Request({
  url: `localhost/api/products`,
  method: RequestMethods.Get
});

this.http.request(req).subscribe(
  res => {
    // Can't access the headers of the response here.... res.headers is empty
  },
  error => { ... },
  _ => {}
);

If I check the network traffic in the browser’s dev tools, the response headers are present…

API (Node Js): res.header(“access-control-expose-headers”, “name-of-expose-header”); res.setHeader(‘name-of-expose-header’, “your-value”); Frontend(Angular): response.headers.get(‘name-of-expose-header’)

Ex: You can replace name-of-expose-header by etag.

@meitix @pkozlowski-opensource correct brother this is API problem.

@santiagomolinadecastro Because Web is designed to be secure, same reason for why I cannot get HTTP-only cookie in JavaScript.

@asanzdiego this is not an Angular issue - Angular gives you all the headers that XHR gives users. Try your example with vanilla https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest ans see what happens.

It is simply that some headers are meant to be interpreted by a browser only and not exposed to the users directly.

If, by any chance, you are getting different results with vanilla XMLHttpRequest please open a new issue with the exact reproduce scenario.