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

Spring整合Angular新增员工触发CORS跨域错误该如何解决?

问题原因

你的CORS配置存在两处核心错误,这是GET请求正常但POST请求触发跨域拦截的根本原因:

  • 未显式声明允许的HTTP请求方法:你将跨域允许的方法规则错误写到了allowedHeaders配置项中,没有单独配置allowedMethods属性,因此POST请求未被放行
  • 允许的请求头列表存在冗余错误内容:Access-Control-Allow-Origin: *、Access-Control-Allow-Methods: GET, DELETE, HEAD, OPTIONS都属于服务端返回的响应头字段,不属于客户端请求头,不应该配置在allowedHeaders中

解决方案

将你的CorsFilter配置替换为如下修正后的内容即可:

@Bean
public CorsFilter corsFilter(){
    CorsConfiguration corsConfiguration= new CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    // 允许的前端源地址
    corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    // 允许的请求头,删除冗余错误内容
    corsConfiguration.setAllowedHeaders(Arrays.asList("Origin","Content-Type","Accept","Authorization",
            "X-Requested-With","Access-Control-Request-Method", "Access-Control-Request-Headers"));
    // 新增允许的请求方法配置,包含POST
    corsConfiguration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS","HEAD"));
    // 允许前端访问的响应头
    corsConfiguration.setExposedHeaders(Arrays.asList("Authorization","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsFilter(source);
}

备选轻量方案(适合小型项目)

如果你不想写全局过滤器配置,也可以直接在对应Controller类上添加@CrossOrigin注解,Spring会自动处理跨域:

@RestController
@RequestMapping("/employee")
@CrossOrigin(origins = "http://localhost:4200", allowCredentials = "true")
public class EmployeeController {
    // 你的接口代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:27:03