react如何设置反向代理
设置反向代理的方法
在 React 项目中设置反向代理可以通过 create-react-app 内置的代理配置或手动配置服务器(如 Nginx)实现。
方法一:使用 create-react-app 的代理配置
在 React 项目的 package.json 中添加 proxy 字段,指向目标后端服务器地址:
{
"proxy": "http://your-backend-server.com"
}
重启开发服务器后,前端发起的 API 请求会自动代理到指定地址。
方法二:自定义代理中间件

若需更灵活配置(如多代理路径),可安装 http-proxy-middleware:
npm install http-proxy-middleware --save
在 src 目录下创建 setupProxy.js 文件:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://your-backend-server.com',
changeOrigin: true,
})
);
};
此配置会将所有 /api 开头的请求代理到目标服务器。

方法三:生产环境 Nginx 配置
在部署时,通过 Nginx 配置反向代理。编辑 Nginx 配置文件(如 /etc/nginx/conf.d/default.conf):
server {
listen 80;
server_name your-domain.com;
location / {
root /path/to/react/build;
try_files $uri /index.html;
}
location /api {
proxy_pass http://your-backend-server.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
重新加载 Nginx 使配置生效:
sudo systemctl reload nginx
注意事项
- 开发环境使用
proxy或http-proxy-middleware需重启开发服务器。 - 生产环境务必通过 Web 服务器(如 Nginx)配置代理,避免直接暴露后端地址。
- 若后端启用 HTTPS,需在代理配置中添加 SSL 相关参数。






