簡體   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