简体   繁体   中英

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

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...

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.

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.

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

Where as I had to specify what the necessary headers I had to expose to the End user from my Server itself by adding what the header(s) really were!

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

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM