You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular读取Spring Boot自定义HTTP Header返回Null求助

问题排查与解决

核心原因是CORS跨域限制:浏览器出于安全考虑,对于非简单响应头(比如你自定义的Authorization),只有在服务端明确配置允许暴露后,前端才能访问到。Postman不受浏览器的CORS规则约束,所以能正常获取所有Header。

解决步骤

在Spring Security的CORS配置中,添加exposedHeaders配置,将需要前端访问的自定义Header列入其中:

修改你的filterChain方法里的CorsConfiguration部分:

@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowCredentials(true);
    config.setAllowedHeaders(Collections.singletonList("*"));
    // 新增这一行:暴露自定义的Authorization响应头
    config.setExposedHeaders(Collections.singletonList("Authorization"));
    config.setMaxAge(3600L);
    return config;
}

如果需要暴露多个自定义Header,可以用Arrays.asList来设置,比如:

config.setExposedHeaders(Arrays.asList("Authorization", "X-Custom-Header"));

验证修改

重启Spring Boot服务后,重新调用Angular的接口,此时res.headers.get('Authorization')应该能正常获取到值。

额外说明

  • 浏览器默认允许前端访问的简单响应头包括:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma,这些不需要额外配置暴露。
  • 你的Angular请求配置已经正确设置了observe: 'response'(用于获取完整响应对象)和withCredentials: true(对应服务端的AllowCredentials),这部分无需修改。

内容的提问来源于stack exchange,提问作者dogteeth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 08:15:24