[英]Angular HttpClient missing response headers
我最近試圖進入角度。 我有一個分頁請求。
const myParams = new HttpParams().set('page', page.toString()).set('size', size.toString());
this.http.get<HttpResponse<User[]>>('https://localhost:8443/user/', {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
params: myParams,
observe: 'response'
}).suscribe((response: HttpResponse<User[]>) => this.data = response.body);
DB 中元素的總數在X-Total-Count
標頭中傳輸到客戶端。 我試着這樣讀:
.suscribe((response: HttpResponse<User[]>) => {
this.data = response.body;
this.totalCount = response.headers.get('X-Total-Count');
});
但這不起作用。 結果是 response.headers 只包含真正的 http-response-headers 的一個子集。
這是 headers 對象的樣子
"headers": {
"normalizedNames": {},
"lazyUpdate": null
}
我確定 X-Total-Count 已發送。 Firefox devtools 顯示了它。 你能告訴我如何將它包含在響應中嗎?
更新
這個問題與在以下方面被確定為重復的問題不同:我沒有詢問如何檢查完整的 httpResponse。 這是我自己想出來的。 我一直在問為什么 Response 的headers
屬性不完整。
CORS 請求僅公開 6 個列入安全名單的標頭: Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
& Pragma
。
為了使用 CORS 請求訪問自定義標頭,服務器必須明確地將它們列入白名單。 這可以通過發送響應頭來完成: Access-Control-Expose-Headers
例如: Access-Control-Expose-Headers: X-Total-Count, X-Paging-PageSize
HttpResponse 對象中的標頭是延遲加載的,因此在您強制加載值之前, headers
將顯示為空。 嘗試調用response.headers.keys()
以查看所有可用的標頭名稱。 順便說一下,這也強制將所有值加載到地圖response.headers.headers
。
嘗試將withCredentials: true
添加到 http 選項對象。
正如 Tsvetan Ganev 之前所說,如果這是 CORS 請求,您需要按名稱在Access-Control-Expose-Headers
標頭中明確公開所需的標頭。 為此,您需要配置應用程序服務器,例如在 Spring 中使用WebMvcConfigurer
您可以公開以下標頭:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("*")
.exposedHeaders("X-Total-Count")
.allowedMethods("*");
}
}
使用此配置,您的瀏覽器將超過 7 個默認標頭:
Cache-Control
Content-Language
Content-Length
Content-Type
Expires
Last-Modified
Pragma
還將為您的應用程序公開X-Total-Count
標頭。
就我而言,郵遞員能夠獲取自定義的“授權”標頭,但 Angular 卻沒有。 我通過顯式公開自定義標頭來解決它
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
// vvv
config.addExposedHeader(HttpHeaders.AUTHORIZATION);
// ^^^
config.addAllowedMethod(HttpMethod.OPTIONS);
config.addAllowedMethod(HttpMethod.GET);
config.addAllowedMethod(HttpMethod.POST);
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.PATCH);
config.addAllowedMethod(HttpMethod.DELETE);
config.setMaxAge(1800L);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.