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

Angular15调用SpringBoot3.0.1 API遇CORS跨域阻塞问题求助

解决Angular 15 + Spring Boot 3.0.1的CORS错误

你遇到的这个错误提示,核心问题大概率不是Spring Boot的CORS配置没生效,而是前端请求的URL格式有问题,或是Spring Security拦截了CORS配置,下面是具体排查和解决步骤:

1. 检查前端请求的API地址格式

确保Angular调用后端API时使用完整带协议的URL,比如必须写 http://localhost:8080/api/xxx,不能只写 localhost:8080/api/xxx 或 /api/xxx(若代理配置未正确设置)。

  • 可查看Angular的 environment.ts 文件,确认API地址配置是完整的 http://localhost:8080 开头。

2. 处理Spring Security对CORS的拦截

如果项目用到Spring Security,仅通过 WebMvcConfigurer 配置CORS会被Security过滤器拦截,需在Security配置中单独开启CORS:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 开启CORS配置
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            // 无需CSRF保护可禁用,避免干扰跨域请求
            .csrf(csrf -> csrf.disable())
            // 其他Security配置(如授权、认证)...
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许前端源地址
        config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
        // 按需设置允许的请求方法,不要仅限制GET
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Collections.singletonList("*"));
        // 若前端需携带Cookie,开启此配置
        config.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

3. 排查其他干扰因素

  • 清除Chrome缓存或用无痕模式测试,避免旧缓存引发的问题。
  • 禁用浏览器广告拦截、隐私类插件,这类插件可能拦截跨域请求。
  • 确认后端服务运行端口(默认8080)正确,可直接在浏览器访问后端API地址,验证是否能正常返回数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:55:19