拦截HTTP响应头
这是我送我的HTTP请求:拦截HTTP响应头
return this.http.get(url, { observe: 'response' })
我想我HttpInterceptor阅读的HttpResponse的HTTP头:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.do(event => {
if (event instanceof HttpResponse) {
this.logger.logDebug(event); // Headers are missing here
}
})
.catch((err: HttpErrorResponse) => {
// Do stuff
}
}
拦截器提供了这样我app.module.ts :
{ 提供:HTTP_INTERCEPTORS, useClass:MyHttpInterceptor, 多:真 }
事件似乎已经没有头,甚至在Chrome浏览器开发控制台我看不到任何标题:
然而,在使用时邮差,我可以看到标题在响应(如预期)
Connection →keep-alive
Content-Length →14766
Content-Type →application/json
Date →Fri, 04 Aug 2017 14:50:46 GMT
Server →WildFly/10
X-Powered-By →Undertow/1
如何在Angular中显示这些标题?
用于HTTP官方docs说,以获得标题是这样的:
http
.get<MyJsonData>('/data.json', {observe: 'response'})
.subscribe(resp => {
// Here, resp is of type HttpResponse<MyJsonData>.
// You can inspect its headers:
console.log(resp.headers.get('X-Custom-Header'));
// And access the body directly, which is typed as MyJsonData as requested.
console.log(resp.body.someField);
});
我找到了答案。这当然是一个CORS问题。我正在使用CORS Filter,我需要明确公开自定义标题。我希望这能最终帮助别人。
谢谢Tim,它让CORS业务疯狂。对于任何对Spring Boot感兴趣的人,您必须将头名添加到CorsRegistry的exposedHeaders方法。 – emvidi
看起来像服务器端CORS过滤器配置。
缺省情况下,只有6个简单的响应报头被暴露:
- 缓存控制
- 内容语言
- 内容类型
- 过期
- 上次修改
- Pragma
如果您希望客户端能够访问其他头文件,则必须使用Access-Control-Expose-Headers头将它们列出。
来源:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
你如何注册这个拦截? – Giovane
我编辑我的帖子,添加此信息 – Tim
Angular的回复中记录了什么? – Giovane