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

Spring Boot/Angular应用中CORS错误无法解决求助

解决Spring Boot + Angular跨域CORS错误的方案

针对你遇到的CORS配置后仍报错的问题,可按以下步骤排查修复:

  • 修正AllowedMethods中的错误方法名
    你的配置里将预检请求需要的OPTIONS方法写成了HEADER,这会导致浏览器发送的OPTIONS预检请求被拒绝,直接修改代码:

    configuration.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
    
  • 补充CORS必要配置项
    仅配置源和方法往往不够,需添加允许的请求头、凭证支持等:

    @Bean
    CorsConfigurationSource apiConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 若前端需携带凭证(如Cookie、Token),需指定具体域名而非*
        configuration.setAllowedOriginPatterns(List.of("http://localhost:4200"));
        configuration.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
        // 允许常用请求头,可根据实际需求调整
        configuration.setAllowedHeaders(List.of("Authorization", "Content-Type", "Accept"));
        // 开启凭证支持,若前端用withCredentials则必须设置
        configuration.setAllowCredentials(true);
        // 暴露后端返回的自定义头(如Authorization)给前端
        configuration.setExposedHeaders(List.of("Authorization"));
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    
  • 确保Security过滤链顺序正确
    在Security Config中,cors配置需放在csrf等其他配置之前,避免被提前拦截:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors(cors -> cors.configurationSource(apiConfigurationSource()))
            .csrf().disable()
            // 其他权限配置...
    }
    
  • 移除冗余的@CrossOrigin注解
    全局CORS配置与控制器上的@CrossOrigin可能产生冲突,建议删除控制器类/方法上的@CrossOrigin,仅保留全局配置。

  • 检查Angular请求配置
    若前端请求需携带凭证,需在HttpClient请求中开启withCredentials:

    import { HttpClient } from '@angular/common/http';
    
    constructor(private http: HttpClient) {}
    
    fetchData() {
      return this.http.get('http://your-backend-url/api/data', { withCredentials: true });
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:40:20