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

如何配置React应用使API请求指向域名而非localhost:8000

问题

已将React应用部署到Vultr服务器,完成Nginx配置后前端可正常访问,但启动后端server.js后,前端API请求仍指向localhost:8000/service/listofblogs,无法正确调用后端接口。

相关配置信息:

  • Nginx配置(/etc/nginx/sites-available/default):
server {
    listen 80;
    server_name somedomain-test.com www.somedomain-test.com;
    root /var/www/somedomain-test.com/build;
    index index.html;
}
  • package.json配置:
{
  "name": "myblogs",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    .....
  },
  "proxy": "http://localhost:8000",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  ....
}
  • .env文件配置:
DANGEROUSLY_DISABLE_HOST_CHECK=true
REACT_APP_URL=http://somedomain-test.com
解决方案

1. 明确:package.json的proxy仅在开发环境生效

Create React App的proxy字段只在本地开发(npm start)时起作用,生产环境构建(npm run build)后该配置不会生效,必须通过其他方式处理API转发。

2. 配置Nginx反向代理(推荐)

修改Nginx配置文件,添加反向代理规则,将前端的API请求转发到后端的8000端口:

  1. 编辑Nginx配置文件:
sudo nano /etc/nginx/sites-available/default
  1. 在server块内新增以下配置:
# 匹配API请求路径,转发到后端服务
location /service {
    proxy_pass http://localhost:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

# 处理React单页应用路由刷新问题(可选但建议添加)
location / {
    try_files $uri $uri/ /index.html;
}
  1. 验证配置并重启Nginx:
sudo nginx -t
sudo systemctl restart nginx

3. 修改前端API请求路径

确保前端代码中使用相对路径或环境变量拼接API地址:

  • 方式一:使用相对路径
    将原来的请求代码:
fetch('http://localhost:8000/service/listofblogs')

改为:

fetch('/service/listofblogs')
  • 方式二:使用环境变量
    利用.env中的REACT_APP_URL拼接地址:
fetch(`${process.env.REACT_APP_URL}/service/listofblogs`)

修改后需重新执行npm run build,并将新的build文件夹同步到服务器的/var/www/somedomain-test.com/build目录。

4. 确保后端服务正常运行

确认server.js在服务器上已启动并监听8000端口,可通过以下命令检查:

netstat -tulpn | grep :8000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:07:22