Angular 2: unable to access response headers in HTTP request

I am using the angular2 -http (alpha.44) module to retrieve data from REST Api. I can’t understand how to access the information coming to the response header card, from which I need a specific field. 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 => { ... }, _ => {} ); 

Oddly enough, if I check the network traffic in the dev browser tools, the response headers are present ...

+5
source share
3 answers

There is already a problem with this problem open on github: -

https://github.com/angular/angular/issues/5237#issuecomment-156059284

Please check it out as someone posted a workaround.

UPDATE

The angular team has already solved this problem.

+4
source

The solution is in an already related problem, but in a later comment: https://github.com/angular/angular/issues/5237#issuecomment-239174349

With the exception of some common headers, only headers listed as the value of the Access-Control-Expose-Headers header will be displayed in Angular2 (possibly with others). This should be added on the server side.

It took me over an hour to find out for the Authorization header. I thought this was not a custom header, but it is.

In PHP, call something like this: header("Access-Control-Expose-Headers: Authorization, X-Custom-header");

If you use Laravel as a backend with barryvdh/laravel-cors , do this in the config/cors.php .

+5
source

I found this link useful: https://developer.mozilla.org/es/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

Where I had to indicate what necessary headers I needed to provide to the End User from my server itself, adding what headers really were!

 // Request headers you wish to expose res.setHeader('Access-Control-Expose-Headers', 'your_desired_header, content-type'); 

Hooray!

+1
source

Source: https://habr.com/ru/post/1235772/


All Articles