简体   繁体   English

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

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

This is how I send my HTTP request:这是我发送HTTP 请求的方式:

return this.http.get(url, { observe: 'response' })

I would like to read the HTTP headers of a HttpResponse in my HttpInterceptor:我想在我的 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
    }
}

The interceptor is provided like this in my app.module.ts:拦截器在我的 app.module.ts 中是这样提供的

{ provide: HTTP_INTERCEPTORS, useClass: MyHttpInterceptor, multi: true } { 提供:HTTP_INTERCEPTORS,useClass:MyHttpInterceptor,multi:true }

The event seems to have no headers , and even in the Chrome Dev Console I cannot see any headers:该事件似乎没有 headers ,即使在 Chrome Dev Console 中我也看不到任何 headers:

在此处输入图片说明

However, when using Postman, I can see the headers in the response (as expected)但是,在使用 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

How can I reveal these headers in Angular ?如何在 Angular 中显示这些标题?

The official docs for HTTP says to get the headers like this: 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);
  });

I found the answer.我找到了答案。 It was (of course) a CORS Problem.这(当然)是一个 CORS 问题。 I am using a CORS Filter and I needed to explicitely expose my custom header.我正在使用CORS 过滤器,我需要明确公开我的自定义标头。 I hope this can help others eventually.我希望这最终可以帮助其他人。

Looks like a server-side CORS filter configuration.看起来像服务器端 CORS 过滤器配置。

By default, only the 6 simple response headers are exposed:默认情况下,只公开 6 个简单的响应头:

  • Cache-Control缓存控制
  • Content-Language内容语言
  • Content-Type内容类型
  • Expires过期
  • Last-Modified上次修改
  • Pragma编译指示

If you want clients to be able to access other headers, you have to list them using the Access-Control-Expose-Headers header.如果您希望客户端能够访问其他标头,则必须使用 Access-Control-Expose-Headers 标头列出它们。

Use Access-Control-Expose-Headers to expose the headers.使用Access-Control-Expose-Headers公开标题。

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

To see the headers, access the 'headers' within the response.要查看标头,请访问响应中的“标头”。 The headers are lazily evaluated it seems, thus they are not visible.标题似乎被懒惰地评估,因此它们不可见。 I suppose that the headers get evaluated only when you explicitly ask for them using resp.headers.get .我想只有当您使用resp.headers.get明确要求标头时,才会对标头进行评估。 However, you can get the list of headers in the response using res.headers.keys() .但是,您可以使用res.headers.keys()获取响应中的标头列表。 Eg.例如。

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

That's not related to Angular.这与 Angular 无关。 The problem is CORS limits headers by default and you do not see " X-Custom-Header " header when call CORS requests.问题是默认情况下 CORS 会限制标头,并且在调用 CORS 请求时看不到“ X-Custom-Header ”标头。 So, adjust server to let it send X-Custom-Header.所以,调整服务器让它发送 X-Custom-Header。

There are TWO different headers that need to be added:两个不同的标题需要添加:

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

Access-Control-Allow-Headers must be provided in response of OPTIONS request (pre-flight).必须提供Access-Control-Allow-Headers以响应 OPTIONS 请求(飞行前)。

Access-Control-Expose-Headers must be provided in response to the actual (POST/GET) request.必须提供Access-Control-Expose-Headers以响应实际的 (POST/GET) 请求。

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

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

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