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

Spring Boot对接React请求被CORS策略拦截问题排查

问题排查与修复方案

根因说明

报错由两个独立问题共同导致,优先级从高到低如下:

1. 前端请求构造错误

从报错日志的请求路径可以直接定位问题:

目标地址http://localhost:8082/customermanagement%E2%80%8B/api%E2%80%8B/services%E2%80%8B/prospect%E2%80%8B/[object%20Object]%E2%80%8B/delete

  • 路径中所有%E2%80%8B是复制路径时带入的不可见零宽空格,会直接导致后端路径匹配404
  • 路径中[object%20Object]是参数拼接语法错误:你写的"prospect​/" + {id} + "​/delete"是将一个新对象{id}与字符串拼接,JS默认将对象转为字符串时就会输出[object Object],实际的id值根本没有被拼入路径
    修正后的前端代码:
const handleDelete = async (id) => {
  console.log(id)
  // 注意手动删除路径中所有不可见的零宽空格,用模板字符串直接插入id变量
  await axios.delete(`http://localhost:8082/customermanagement/api/services/prospect/${id}/delete`)
    .then(() => console.log('Delete successful'));
}

2. 后端CORS配置缺失

你在Spring Security配置中仅开启了.cors()开关,但没有提供对应的CORS规则配置,Spring Security内置的CorsFilter会因为找不到匹配规则,不会给响应添加Access-Control-Allow-Origin头。
另外Controller类上的@CrossOrigin(origins = "*")注解在请求经过Spring Security过滤器链之后才会生效,浏览器发的预检OPTIONS请求会被Security的认证规则直接拦截,根本到不了Controller层,自然不会携带CORS响应头。
后端修复步骤:

  • 在SecurityConfig类中添加CORS配置源Bean:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    // 开发环境允许本地前端源,生产环境替换为实际前端域名,不要用*
    config.setAllowedOriginPatterns(List.of("http://localhost:3000"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    config.setAllowedHeaders(List.of("*"));
    config.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}
  • 在Security的权限规则中添加OPTIONS请求全局放行,避免预检请求被认证拦截,同时显式指定CORS配置源:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .cors().configurationSource(corsConfigurationSource())
            .and()
            .csrf()
            .disable()
            .authorizeRequests()
            // 放行所有OPTIONS预检请求
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(AUTH_WHITELIST)
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .exceptionHandling()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
  • 可以删掉Controller上的@CrossOrigin注解,全局CORS配置已经覆盖了所有接口的跨域需求。

修复完成后重启后端服务,清空浏览器缓存再发起请求即可正常访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:18:19