
本文详解如何在 spring boot 中正确配置 cors,解决 angular 前端(http://localhost:4200)调用后端接口(http://localhost:8090)时因预检失败导致的 “request header field domain is not allowed by access-control-allow-headers” 错误。
在前后端分离开发中,Angular 运行于 http://localhost:4200,而 Spring Boot 后端部署在 http://localhost:8090,浏览器会因同源策略触发跨域检查(CORS)。你遇到的错误:
Access to XMLHttpRequest at 'http://localhost:8090/bites/service/signup' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field domain is not allowed by Access-Control-Allow-Headers in preflight response.
关键线索在于 Request header field domain —— 这说明你的 Angular 请求中包含了自定义请求头(例如 domain),但 Spring Boot 的 CORS 配置未将其列入 Access-Control-Allow-Headers 白名单,导致预检(OPTIONS)响应被拒绝。
⚠️ 注意:你当前手动在 Filter 中设置响应头的方式存在严重隐患:
- 未处理 OPTIONS 预检请求的短路逻辑(即对 OPTIONS 请求应直接返回,不执行 chain.doFilter());
- Access-Control-Allow-Headers 值未包含 domain,且硬编码的 Header 列表冗长、易遗漏;
- WebMvcConfigurerAdapter 在 Spring Boot 2.4+ 已被弃用,新版本需使用函数式配置。
✅ 推荐方案:采用 Spring Boot 官方推荐的 WebMvcConfigurer Bean 方式统一管理 CORS,简洁、安全、可维护。
✅ 正确配置方式(Spring Boot 2.4+)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/bites/**") // 精准匹配 API 路径(推荐)
.allowedOrigins("http://localhost:4200")
.allowCredentials(true)
.allowedHeaders("Origin", "X-Requested-With", "Content-Type",
"Accept", "Key", "Authorization", "domain") // ✅ 显式添加 'domain'
.maxAge(3600);
}
};
}
}? 小提示:/bites/** 比 /** 更安全,避免对静态资源或管理端点误开 CORS;如需全局开放,可保留 /**,但请确保生产环境严格限制 allowedOrigins(禁用 "*" 配合 allowCredentials(true))。
✅ 补充:若需支持更多自定义 Header(如 X-Trace-ID)
只需在 allowedHeaders(...) 中追加即可:
.allowedHeaders("Origin", "X-Requested-With", "Content-Type",
"Accept", "Key", "Authorization", "domain", "X-Trace-ID")⚠️ 重要注意事项
- allowCredentials(true) 必须配 allowedOrigins 具体域名:不可使用 "*",否则浏览器将拒绝该配置;
-
Angular 请求需显式启用凭据:确保 HTTP 调用中设置了 withCredentials: true:
// Angular service 示例 this.http.post('/bites/service/signup', data, { withCredentials: true }) - 移除旧 Filter 中的手动 CORS 设置:避免与 WebMvcConfigurer 冲突,造成响应头重复或覆盖;
- 检查是否启用了 Spring Security:若已引入 spring-boot-starter-security,需额外配置 Security 层允许 CORS(见下文)。
? Spring Security 用户额外配置(如适用)
若项目集成 Spring Security,请在安全配置类中启用 CORS 并委托给 MVC 配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Arrays.asList(
"Origin", "X-Requested-With", "Content-Type",
"Accept", "Key", "Authorization", "domain"
));
config.setMaxAge(3600L);
return config;
}))
.csrf(csrf -> csrf.disable()) // 开发阶段可禁用,生产务必启用并配置
.authorizeHttpRequests(authz -> authz
.requestMatchers("/bites/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}✅ 总结
| 问题根源 | 解决动作 |
|---|---|
| 自定义请求头 domain 未被允许 | 在 allowedHeaders 中显式添加 "domain" |
| 手动 Filter 配置不完整/有缺陷 | 改用 WebMvcConfigurer.addCorsMappings() 标准方式 |
| 凭据与通配符冲突 | allowCredentials(true) + allowedOrigins("http://localhost:4200") 组合使用 |
| 生产环境风险 | 禁用 allowedOrigins("*"),按环境配置白名单 |
完成配置后重启 Spring Boot 应用,Angular 发起的带 domain 头的 POST 请求将顺利通过预检,成功完成注册流程。










