Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Can't access response headers in a http request

Tags:

angular

I'm using angular2-http(alpha.44) module to retrieve data from a REST Api. I can't figure out how to access the information that comes in the headers map of the response, 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 => { ... },
  _ => {}
);

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

like image 651
cangosta Avatar asked Nov 12 '15 10:11

cangosta


2 Answers

The solution is in the already linked issue but in a later comment: https://github.com/angular/angular/issues/5237#issuecomment-239174349

Except for some generic headers only the headers listed as a value of Access-Control-Expose-Headers header will be mapped in Angular2 (maybe with others too). This has to be added on backend side.

For me it took more than an hour to find this out for Authorization header. I thought it is not that 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 backend with barryvdh/laravel-cors do this setup in the config/cors.php file.

like image 121
Manuel Fodor Avatar answered Oct 27 '22 17:10

Manuel Fodor


There is already an issue about that problem opened on github:-

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

Please check it, as someone posted a workaround.

UPDATE

The angular team has already solved this problem.

like image 4
Bruno Cunha e Silva Avatar answered Oct 27 '22 16:10

Bruno Cunha e Silva