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

已用@CrossOrigin仍遇CORS拦截问题求助(Spring Boot+React跨域)

解决Spring Boot @CrossOrigin失效的CORS问题

排查方向及解决方案

  • 补全@CrossOrigin的属性配置
    仅用@CrossOrigin默认配置可能不覆盖PUT/DELETE这类非简单请求,你的updatePost接口大概率是PUT方法,需明确指定允许的源、请求方法和头:

    @CrossOrigin(origins = "http://localhost:3000", 
                 methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE},
                 allowedHeaders = "*")
    
  • 处理Spring Security的拦截优先级
    如果项目用了Spring Security,它的拦截规则会优先于@CrossOrigin,必须在Security配置类中添加CORS配置:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .csrf(csrf -> csrf.disable()); // 前后端分离场景通常需关闭CSRF,或配置令牌
            return http.build();
        }
    
        @Bean
        public CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
            config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            config.setAllowedHeaders(Arrays.asList("*"));
            config.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", config);
            return source;
        }
    }
    

    注意:浏览器会先发送OPTIONS预检请求,必须确保该请求能被Spring Security放行。

  • 确认请求方法与控制器注解匹配
    检查updatePost方法是否标注了正确的请求注解(比如@PutMapping),如果控制器方法不支持对应的请求类型,也会触发CORS类错误。

  • 检查注解标注位置
    确保@CrossOrigin标注在控制器类或对应的请求方法上,类上的注解对所有方法生效,方法上的注解会覆盖类配置。

  • 清除浏览器缓存
    旧的CORS缓存可能导致异常,清除缓存后重新发起请求测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:20:30