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

如何解决React与Spring Boot项目交互时的CORS跨域问题?

React与Spring Boot交互CORS跨域问题解决方案

问题根因

  1. 前端错误添加CORS响应头:Access-Control-* 系列头是服务端返回给浏览器的响应头,前端请求中添加这类头会被视为自定义请求头,触发预检请求校验,且你添加的Access-Control-Allow-Origin值为后端地址,完全不符合规则。
  2. Spring CORS配置未放行Authorization头:你请求使用了Basic Auth认证,会自动携带Authorization请求头,但你的Spring CORS配置里allowedHeaders仅配置了Origin、Content-Type、Accept三个头,未包含Authorization,预检请求会被直接拦截。
  3. 若集成了Spring Security,未显式开启CORS支持:Spring Security会默认拦截所有跨域预检OPTIONS请求,不会走你自定义的CORS过滤器。
  4. 前端请求添加了无用的httpsAgent:你的请求地址是HTTP协议的http://localhost:8080,配置HTTPS代理完全无效,还可能引发请求异常。

直接在浏览器地址栏访问接口正常是因为该场景属于同域简单请求,不会触发浏览器跨域校验规则,也不会触发预检请求,因此可以正常返回结果。


修复步骤

步骤1:修复前端请求代码

直接删掉所有Access-Control-*开头的请求头,移除无用的httpsAgent配置,修改后代码如下:

let url = "http://localhost:8080/test/cox";
try {
  const res = await axios.get(url, {
    auth: {
      username: 'user',
      password: '123456'
    },
    headers: {
      'Content-Type': 'application/json'
    }
  })
  console.log(res)
} catch (err) {
  console.log(err)
}

步骤2:修复Spring Boot CORS配置

修改全局CORS过滤器,添加Authorization头到允许列表,可选添加预检请求缓存时间减少重复预检:

@Component
public class CorsingFilter {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 生产环境不要使用该配置,请替换为合法的允许源地址列表
        config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
        // 新增Authorization头允许,也可以用config.setAllowedHeaders(Collections.singletonList("*"))通配
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        // 预检请求缓存1小时,单位秒
        config.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

步骤3:若集成Spring Security,添加CORS支持

在你的Spring Security配置类中,显式开启CORS支持,避免Security拦截预检请求:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 开启CORS支持,会自动读取你配置的CorsFilter
            .cors()
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
        // 其他你的Security配置保持不变
    }
}

步骤4:移除重复CORS配置(可选)

你已经配置了全局CORS过滤器,接口上的@CrossOrigin注解可以直接删除,避免两种配置规则冲突。


内容的提问来源于stack exchange,提问作者Vlad Paul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:27:02