使用Angular 4.3的HttpInterceptor拦截HTTP响应标头

Tim*_*Tim 7 http-headers angular

这是我发送HTTP请求的方式:

return this.http.get(url, { observe: 'response' })
Run Code Online (Sandbox Code Playgroud)

我想在我的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
    }
}
Run Code Online (Sandbox Code Playgroud)

拦截器在我的app.module.ts中是这样提供的

{提供:HTTP_INTERCEPTORS,useClass:MyHttpInterceptor,多:true}

该事件似乎没有标题,即使在Chrome开发者控制台中,我也看不到任何标题:

在此处输入图片说明

但是,使用Postman时,我可以在响应中看到标题(如预期的那样)

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
Run Code Online (Sandbox Code Playgroud)

如何在Angular中显示这些标题?

HTTP 的官方文档说要获得如下标头:

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);
  });
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 5

我找到了答案。(当然)这是一个CORS问题。我正在使用CORS筛选器,并且需要显式公开我的自定义标头。我希望这最终可以帮助其他人。

  • 感谢Tim,这使CORS业务疯狂。对于任何对Spring Boot感兴趣的人,您都必须将标题名称添加到CorsRegistry的暴露的方法中。 (3认同)