Spring+React多服务器部署时,如何配置跨API服务器请求?
解决React请求API服务器的配置问题
首先要明确:你用的package.json里的proxy字段只在React开发环境(create-react-app的dev server)生效,生产环境打包后这个配置完全没用——因为打包后的React是静态文件,没有dev server帮你做请求转发。下面分两种场景给你解决方案:
一、开发环境(本地调试)
如果是本地跑dev server时请求不对,按以下步骤排查:
- 确认
package.json的proxy配置正确,直接写API服务器的根地址:"proxy": "http://localhost:9090" - 检查你的请求代码,不要手动给路径加
localhost:8880,保持相对路径/api/person/all即可 - 如果还是不生效,可能是create-react-app版本问题,需要手动配置代理:
- 安装依赖:
npm install http-proxy-middleware --save-dev - 在
src目录下新建setupProxy.js文件:const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://localhost:9090', changeOrigin: true, }) ); };
/api/person/all就会自动转发到http://localhost:9090/api/person/all - 安装依赖:
二、生产环境(部署到UI服务器)
打包后的React是静态文件,必须用以下两种方案之一:
方案1:在React代码中配置全局API地址(简单直接)
- 在
src下新建config.js:// 根据环境自动切换地址,生产环境换成API服务器的公网IP/域名 export const API_BASE_URL = process.env.NODE_ENV === 'production' ? 'http://你的API服务器IP:9090' : 'http://localhost:9090'; - 在请求代码中引入并使用:
注意:这种方式需要在API服务器上配置CORS跨域允许,允许UI服务器的地址发起请求。import { API_BASE_URL } from './config'; // 用fetch的例子 fetch(`${API_BASE_URL}/api/person/all`) .then(res => res.json()) .then(data => console.log(data)); // 用axios的例子(更推荐) import axios from 'axios'; axios.defaults.baseURL = API_BASE_URL; axios.get('/api/person/all').then(res => console.log(res.data));
方案2:UI服务器配置反向代理(推荐,避免跨域)
通过UI服务器(Spring或Nginx)转发请求,这样浏览器请求的是同域地址,不会触发跨域限制:
如果UI服务器是Spring Boot:
可以用Spring Cloud Gateway做代理,添加依赖和配置:
- pom.xml添加依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> - application.yml配置:
这样所有spring: cloud: gateway: routes: - id: api-proxy uri: http://你的API服务器IP:9090 predicates: - Path=/api/**/api/**的请求都会被Spring转发到API服务器。
如果用Nginx部署React静态文件:
修改Nginx配置文件:
server { listen 8880; # UI服务器端口 server_name 你的UI服务器IP; # 处理React静态文件和路由 location / { root /path/to/react/build; # React打包后的dist/build目录 index index.html; try_files $uri $uri/ /index.html; # 解决路由刷新404问题 } # 代理API请求 location /api/ { proxy_pass http://你的API服务器IP:9090/; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
重启Nginx后,UI上的/api/person/all请求会自动转发到API服务器。
内容的提问来源于stack exchange,提问作者hhrzc
相关产品推荐
相关产品推荐

