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

ReactJS应用调用AWS EC2接口遭CORS拦截问题求助

React调用Spring Boot接口遇CORS拦截的原因与解决办法

问题原因

  • 浏览器的同源策略限制:你的React应用运行在localhost:3000,EC2上的接口属于另一个域名+端口,属于跨域请求。浏览器会自动发起CORS预检请求(OPTIONS),如果后端Spring Boot没有配置允许跨域的响应头(Access-Control-Allow-Origin),浏览器就会拦截请求结果,抛出你看到的错误。
  • Postman或浏览器直接访问地址时,不会触发浏览器的CORS校验逻辑,所以能正常获取数据。

解决办法

方案一:在Spring Boot后端配置CORS(生产环境推荐)

这是从根源解决跨域问题的方式,有两种配置方式:

1. 全局CORS配置(对所有接口生效)

创建一个配置类,统一设置跨域规则:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许本地开发环境的React访问,生产环境替换为前端实际域名
        config.addAllowedOrigin("http://localhost:3000");
        // 允许所有HTTP请求方法(GET/POST等)
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许携带Cookie等凭证(如果业务需要)
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 规则应用到所有接口路径
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
2. 接口级局部配置

如果只想给特定接口开启跨域支持,可以在Controller类或方法上添加@CrossOrigin注解:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 允许localhost:3000访问该类下所有接口
@CrossOrigin(origins = "http://localhost:3000")
public class SearchController {
    @GetMapping("/searchAll")
    public List<YourDataModel> searchAll() {
        // 接口业务逻辑
        return yourDataList;
    }
}

方案二:React开发环境临时代理(仅本地开发用)

如果暂时不想修改后端,可以通过React代理转发请求,绕过浏览器的跨域检查:

  1. 安装代理依赖:
npm install http-proxy-middleware --save-dev
  1. 在项目src目录下创建setupProxy.js文件,添加代理配置:
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://ec2-3-145-165-206.us-east-2.compute.amazonaws.com:8080',
      changeOrigin: true,
      pathRewrite: {
        '^/api': '', // 去掉请求URL中的/api前缀,转发到后端实际接口
      },
    })
  );
};
  1. 修改React中的请求代码:
async function fetchTableData() {
    setLoading(true)
        
    const URL = "/api/searchAll" // 改为代理路径
    const response = await fetch(URL)

    const users = await response.json()
    setData(users)
    setLoading(false)
}

重启React项目后,请求会通过本地代理转发,不再触发CORS拦截。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:02:16