2017-08-04 238 views
3

這是我送我的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瀏覽器開發控制檯我看不到任何標題:

enter image description here

然而,在使用時郵差,我可以看到標題在響應(如預期)

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); 
    }); 
+0

你如何註冊這個攔截? – Giovane

+0

我編輯我的帖子,添加此信息 – Tim

+0

Angular的回覆中記錄了什麼? – Giovane

回答

1

我找到了答案。這當然是一個CORS問題。我正在使用CORS Filter,我需要明確公開自定義標題。我希望這能最終幫助別人。

+1

謝謝Tim,它讓CORS業務瘋狂。對於任何對Spring Boot感興趣的人,您必須將頭名添加到CorsRegistry的exposedHeaders方法。 – emvidi