[英]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. 我正在使用angular2-http(alpha.44)模块从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 该解决方案已在已经链接的问题中,但在稍后的评论中: 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). 除了一些通用标头之外,只有列为
Access-Control-Expose-Headers
标头值的标头才会在Angular2中映射(也可能与其他标头一起映射)。 This has to be added on backend side. 这必须在后端添加。
For me it took more than an hour to find this out for Authorization
header. 对我而言,需要一个多小时才能找到
Authorization
标题。 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");
在PHP中调用类似这样的东西:
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. 如果您使用Laravel作为
barryvdh/laravel-cors
后端,请在config/cors.php
文件中进行此设置。
There is already an issue about that problem opened on github:- 关于在github上打开的问题已经存在一个问题: -
https://github.com/angular/angular/issues/5237#issuecomment-156059284 https://github.com/angular/angular/issues/5237#issuecomment-156059284
Please check it, as someone posted a workaround. 请检查一下,因为有人发布了一个解决方法。
UPDATE 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 我发现此链接很有用: 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! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.