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

Nginx反向代理路径在Node.js Express应用中失效问题排查

Nginx代理Express API返回Cannot GET /api问题解决

问题背景

在Linux服务器上用Nginx+PM2部署React前端与Node.js Express API:

  • React build文件部署在/var/www/example.com/html
  • Express API通过PM2运行在3000端口
  • Nginx配置了/api路径代理到http://localhost:3000,但访问服务器IP/api时页面返回Cannot GET /api
  • Express的server.ts仅配置了根路径的GET路由:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get("/", (_req, res) => {
  res.send("API Running");
});

核心原因

Nginx的proxy_pass http://localhost:3000;会将请求/api完整转发到Express的/api路径,但你的Express服务并没有配置/api路由,只有根路径/的路由,因此返回404错误。

两种解决方式

方式一:修改Nginx配置,重写请求路径

让Nginx将/api开头的请求转发到Express的根路径,有两种实现方式:

  1. 添加末尾斜杠到proxy_pass
    修改Nginx的location /api块:
location /api {
    proxy_pass http://localhost:3000/;  # 注意末尾的斜杠
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

末尾的斜杠会让Nginx自动将/api映射到Express的/,/api/users映射到/users。

  1. 使用rewrite规则重写路径
    如果需要更灵活的路径控制,可添加rewrite规则:
location /api {
    rewrite ^/api(.*)$ $1 break;  # 去掉/api前缀
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

方式二:修改Express路由,添加/api前缀

在Express中为路由添加/api前缀,匹配Nginx的转发路径:

直接修改路由路径

app.get("/api", (_req, res) => {
  res.send("API Running");
});

使用Router挂载前缀(更适合多路由场景)

const router = express.Router();

// 定义路由
router.get("/", (_req, res) => {
  res.send("API Running");
});
// 可添加更多路由,如router.get("/users", ...)

// 将Router挂载到/api路径
app.use("/api", router);

验证步骤

  1. 修改配置后,重新加载Nginx:
sudo systemctl reload nginx
  1. 重启Express服务(如果修改了Express代码):
pm2 restart <你的服务名称>
  1. 确认3000端口正常监听:
netstat -tulpn | grep 3000
  1. 再次访问服务器IP/api,应返回API Running。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:31:02