繁体   English   中英

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

[英]Intercepting HTTP Response headers with Angular 4.3's HttpInterceptor

这是我发送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,multi:true }

该事件似乎没有 headers ,即使在 Chrome Dev Console 中我也看不到任何 headers:

在此处输入图片说明

但是,在使用 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

如何在 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);
  });

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

看起来像服务器端 CORS 过滤器配置。

默认情况下,只公开 6 个简单的响应头:

  • 缓存控制
  • 内容语言
  • 内容类型
  • 过期
  • 上次修改
  • 编译指示

如果您希望客户端能够访问其他标头,则必须使用 Access-Control-Expose-Headers 标头列出它们。

使用Access-Control-Expose-Headers公开标题。

来源: https : //developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

要查看标头,请访问响应中的“标头”。 标题似乎被懒惰地评估,因此它们不可见。 我想只有当您使用resp.headers.get明确要求标头时,才会对标头进行评估。 但是,您可以使用res.headers.keys()获取响应中的标头列表。 例如。

yourFunction.subscribe((res:HttpResponse<any>)=>{console.log('response from server:',res);
      console.log('response headers',res.headers.keys())
    } );

这与 Angular 无关。 问题是默认情况下 CORS 会限制标头,并且在调用 CORS 请求时看不到“ X-Custom-Header ”标头。 所以,调整服务器让它发送 X-Custom-Header。

两个不同的标题需要添加:

  1. Access-Control-Allow-Headers
  2. Access-Control-Expose-Headers

必须提供Access-Control-Allow-Headers以响应 OPTIONS 请求(飞行前)。

必须提供Access-Control-Expose-Headers以响应实际的 (POST/GET) 请求。

Access-Control-Expose-Headers:X-Custom-Header

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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