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

React请求Spring Boot后端遇CORS错误或空响应问题求助

解决fetch请求Spring Boot后端的CORS问题

问题根源

浏览器的同源策略会限制前端页面跨域请求API,mode:"no-cors"看似关闭CORS,实则会让浏览器禁止读取响应内容(返回空响应);而Postman、Node.js环境下的纯JS不受浏览器同源策略约束,所以能正常拿到结果。


方案1:后端配置CORS(标准解决方案)

浏览器环境下必须通过后端开启CORS才能正常跨域请求API,两种配置方式可选:

方式A:接口级CORS注解

直接在接口方法上添加@CrossOrigin,指定允许的前端域名:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

 // 替换为你的前端实际域名(比如React默认的http://localhost:3000)
 @CrossOrigin(origins = "http://localhost:3000")
 @GetMapping
 public String hello() {
  return "hello";
 }
}

方式B:全局CORS配置

如果有多个接口,全局配置更高效:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootApplication
@RestController
public class DemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

 @GetMapping
 public String hello() {
  return "hello";
 }

 @Bean
 public CorsFilter corsFilter() {
  CorsConfiguration config = new CorsConfiguration();
  config.addAllowedOrigin("http://localhost:3000"); // 前端域名
  config.addAllowedMethod("*"); // 允许所有请求方法
  config.addAllowedHeader("*"); // 允许所有请求头
  config.setAllowCredentials(true); // 需要携带Cookie时开启

  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  source.registerCorsConfiguration("/**", config); // 对所有接口生效
  return new CorsFilter(source);
 }
}

方案2:前端代理(仅开发环境可用)

不想修改后端的话,开发环境可以用React代理转发请求,绕过同源策略:

  1. 在React项目的package.json中添加代理配置:
"proxy": "http://localhost:8080"
  1. 修改前端fetch代码为相对路径:
useEffect(() => {
  fetch('/') // 代理会自动转发到http://localhost:8080
    .then(response => response.text())
    .then(text => setResponse(text))
    .catch(error => console.error('Error:', error));
}, []); 

重启React项目后,开发环境的跨域请求即可正常工作。


为什么mode:"no-cors"无效?

设置mode:"no-cors"时,浏览器确实不会发送CORS预检请求,但同时会完全限制读取响应内容(响应状态码为0、body为null),仅适用于无需处理响应的场景(如加载图片、静态脚本),不适合API请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 02:23:21