React+SpringBoot代理请求失败,后端数据无法获取求助
解决React代理SpringBoot接口的[hpm]错误及数据获取问题
排查步骤及解决方法
先确认后端服务正常可用
直接在浏览器输入http://127.0.0.1:8080/api/test,如果能返回test api,说明后端没问题;如果不行,先启动SpringBoot服务,检查端口8080是否被占用,Controller的路径是否正确。检查代理配置的版本与位置
- 确保
http-proxy-middleware是最新版本,旧版本写法不同。可以执行npm install http-proxy-middleware --save重新安装。 setupProxy.js必须放在React项目的src目录下,放在其他位置不会生效。
- 修正代理配置的路径重写
给代理配置添加pathRewrite,避免路径匹配异常:
const{createProxyMiddleware} = require('http-proxy-middleware'); module.exports = function (app){ app.use( '/api', createProxyMiddleware({ target:'http://127.0.0.1:8080', changeOrigin:true, pathRewrite: { '^/api': '/api' } // 显式指定路径重写,确保请求正确转发 }) ); };
- 检查前端请求细节
- 查看浏览器控制台的Network面板,看请求的状态码:
- 404:说明代理没转发到正确的后端路径,检查代理配置的target和pathRewrite;
- 500:后端服务出错,检查SpringBoot的日志;
- 跨域错误:需要在后端添加跨域支持。
- 可以给Axios添加baseURL确保请求路径正确:
// 在App.js开头添加 axios.defaults.baseURL = 'http://localhost:3000';
- 添加SpringBoot跨域支持
虽然代理已处理跨域,但如果后端有安全配置,可能需要显式开启跨域:
- 局部配置:在Controller上添加注解
@RestController @CrossOrigin(origins = "http://localhost:3000") public class TestController { @GetMapping("/api/test") public String text(){ return "test api"; } }
- 全局配置:创建跨域配置类
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true); } }
- 重启服务
修改代理或后端配置后,必须重启React开发服务器和SpringBoot服务,确保配置生效。
内容的提问来源于stack exchange,提问作者sera
相关产品推荐
相关产品推荐

