Angular HttpClient 缺少响应 headers

Angular HttpClient missing response headers

我最近想进入 angular。 我有一个分页请求。

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 header 中传输到客户端。我试着这样读:

.suscribe((response: HttpResponse<User[]>) => {
    this.data = response.body;
    this.totalCount = response.headers.get('X-Total-Count');
});

但这不起作用。原来response.headers只包含了真正的http-response-headers.

的一个子集

这就是 header 的 object 的样子

"headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  }

我确定 X-Total-Count 已发送。 Firefox devtools 显示它。您能告诉我如何将其包含在回复中吗?

更新

这个问题在以下方面与被识别为重复的问题不同:我没有问过如何检查完整的 httpResponse。我自己想出来的。一直在问为什么Response的headers属性不完整

CORS 请求仅公开 6 个安全列表 header:Cache-Control Content-Language Content-Type Expires Last-Modified & Pragma.

为了使用 CORS 请求访问自定义 header,服务器必须明确地将它们列入白名单。这可以通过发送响应 header: Access-Control-Expose-Headers

来完成

例如: Access-Control-Expose-Headers: X-Total-Count, X-Paging-PageSize

MDN Source

尝试将 withCredentials: true 添加到 http 选项对象。

HttpResponse object 中的 header 是 lazy-loaded,因此 headers 将显示为空,直到您强制加载值。尝试调用 response.headers.keys() 以查看所有可用的 header 名称。顺便说一句,这也强制将所有值加载到地图 response.headers.headers.

正如 Tsvetan Ganev 之前所说,如果这是 CORS 请求,您需要按名称在 Access-Control-Expose-Headers header 中明确公开所需的 header。为此,您需要配置应用程序服务器,例如在 Spring 中使用 WebMvcConfigurer 时,您可以公开 headers,例如:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedOrigins("*")
                .exposedHeaders("X-Total-Count")
                .allowedMethods("*");
    }
}

使用这个配置,你的浏览器,超越7默认headers:

  • Cache-Control
  • Content-Language
  • Content-Length
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

也会为您的应用公开 X-Total-Count header。

在我的例子中,Postman 能够获取自定义“授权”header,但 Angular 不能。我通过显式公开自定义 header

解决了这个问题
@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);
}