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

Angular与Spring Boot项目CORS错误排查求助

排查CORS错误的核心方向

1. 验证Spring Boot跨域配置有效性

  • 确认WebConfig类正确实现WebMvcConfigurer,且addCorsMappings覆盖了前端请求的关键维度:
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**") // 覆盖所有需要跨域的接口路径
                    .allowedOrigins("http://localhost:4200") // 严格匹配前端运行地址,不要带末尾斜杠
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 必须包含OPTIONS预检请求
                    .allowedHeaders("*")
                    .allowCredentials(true); // 前端带Cookie/认证信息时必须开启
        }
    }
    
  • 若使用Spring Security,必须额外放行OPTIONS请求,否则预检请求会被拦截:
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行OPTIONS请求
                // 其他权限规则...
        }
    }
    

2. 核对Controller与前端请求的路径匹配

  • 确认Angular请求的URL和Spring Boot Controller的@PostMapping/@RequestMapping路径完全一致,比如前端请求/api/chests,Controller不能写成/chests。
  • 若Controller用了@CrossOrigin注解,需确保注解参数和全局配置不冲突(注解优先级高于全局配置)。

3. 检查Angular端请求配置

  • 若后端开启了allowCredentials,前端必须对应设置withCredentials: true:
    createChest(chest: Chest): Observable<Chest> {
      const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
      return this.http.post<Chest>(`${this.apiUrl}/chests`, chest, {
        headers: headers,
        withCredentials: true
      });
    }
    
  • 确认前端请求的Origin和后端allowedOrigins完全匹配,比如前端运行在http://localhost:4200,后端不能写成http://localhost。

4. 从错误截图提取关键信息

  • 查看预检请求(OPTIONS)的响应状态:若为403,基本是Spring Security拦截了OPTIONS请求;
  • 检查响应头是否包含Access-Control-Allow-Origin等CORS字段,没有则说明后端配置未生效;
  • 确认请求的Origin是否在后端允许的列表内。

5. 其他排查点

  • 若有反向代理(如Nginx),需检查代理配置是否覆盖了CORS响应头;
  • 确保Spring Boot应用已重启,配置修改后必须重启生效;
  • 清理浏览器缓存或用无痕模式测试,排除缓存干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 07:46:00