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

React.js使用Fetch请求Spring Boot接口报CORS跨域错误如何解决?

问题原因

这是浏览器同源策略限制导致的跨域资源共享(CORS)报错:你的React前端通常运行在http://localhost:3000,Spring Boot后端运行在http://localhost:8080,端口不同不属于同源,浏览器会自动校验响应头的Access-Control-Allow-Origin字段,后端没有返回对应字段就会拦截响应。

解决方案

所有方案都在Spring Boot后端实现即可,无需修改React代码,也不要按照报错提示设置mode: 'no-cors'(该模式下无法读取响应数据,仅适用于特殊场景)。

方案1:单Controller/接口配置(灵活度高)

直接在PostController类上添加@CrossOrigin注解,允许前端源访问:

@RestController
@RequestMapping("/posts")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:3000") // 新增这行,指定允许的前端地址
public class PostController {
    private final PostService postService;
    @GetMapping
    public List<Post> getAllPosts(@RequestParam Optional<Long> userId){
       return postService.getAllPosts(userId);
    }
}
  • 允许多个源可以写成@CrossOrigin(origins = {"http://localhost:3000", "http://其他允许的域名"})
  • 本地测试阶段可以临时写@CrossOrigin(origins = "*")允许所有源,生产环境禁止这么配置

方案2:全局CORS配置(适合多接口需要跨域的场景)

新增一个CORS配置类,统一配置所有接口的跨域规则:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 匹配所有后端接口
                .allowedOrigins("http://localhost:3000") // 允许的前端源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
                .allowedHeaders("*") // 允许携带的请求头
                .allowCredentials(true); // 允许跨域携带Cookie,按需开启
    }
}

方案3:Spring Security适配配置

如果你的项目集成了Spring Security,需要额外开启CORS支持,否则上述配置会被拦截:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and() // 开启CORS支持
            .csrf().disable() // 前后端分离项目可关闭CSRF校验
            // 其他你原有Security配置保持不变
            ;
    }
}
验证方式

配置完成后重启Spring Boot应用,重新发起前端请求即可正常拿到接口数据。

内容的提问来源于stack exchange,提问作者Emre Varol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:21:02