Angular 2: 无法访问 http 请求中的响应 headers

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

我正在使用 angular2-http(alpha.44) 模块从 REST Api 检索数据。我不知道如何访问响应的 headers 映射中的信息,我需要从中获取特定字段。示例:

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 => { ... },
  _ => {}
);

奇怪的是,如果我在浏览器的开发工具中检查网络流量,响应 headers 存在...

已经有一个关于 github 上打开的问题的问题:-

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

请查看,因为有人发布了解决方法。

更新

angular团队已经解决了这个问题。

解决方案在已经链接的问题中,但在稍后的评论中:https://github.com/angular/angular/issues/5237#issuecomment-239174349

除了一些通用的 headers,只有 headers 被列为 Access-Control-Expose-Headers header 的值将被映射到 Angular2 中(也可能与其他人一起映射)。这必须在后端添加。

我花了一个多小时才找到 Authorization header。我认为这不是那种习俗 header 但它是。

在 PHP 中调用如下: header("Access-Control-Expose-Headers: Authorization, X-Custom-header");

如果您使用 Laravel 作为 barryvdh/laravel-cors 的后端,请在 config/cors.php 文件中进行此设置。

我发现这个 link 很有帮助: https://developer.mozilla.org/es/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

因为我必须通过添加 header(s) 的真实含义来指定我必须从我的服务器本身向最终用户公开哪些必要的 headers !

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

干杯!