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

Express服务器路由处理器在CRA React应用Vercel部署后异常

问题描述

使用CRA创建的React应用部署到Vercel后,访问/ping路由时返回的是构建生成的index.html文件,而非预期的pong响应;但本地构建运行时该路由功能正常。

Express服务器代码如下:

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();

app.use(express.static(path.join(__dirname, "build")));

app.get("/ping", function (req, res) {
  return res.send("pong");
});

// app.get("*", (req, res) => {
//   res.sendFile(path.join(__dirname, "build", "index.html"));
// });

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

文件结构:
文件结构截图

解决方案

方案1:适配Vercel Serverless Functions规范

Vercel默认优先处理静态文件,需通过配置将接口路由转发到Serverless函数:

  1. 在项目根目录新建api文件夹,创建api/ping.js文件,写入接口逻辑:
module.exports = (req, res) => {
  res.send("pong");
};
  1. 根目录创建vercel.json,添加重写规则:
{
  "rewrites": [
    { "source": "/ping", "destination": "/api/ping" },
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

此配置会将/ping请求转发到Serverless函数处理,其余请求返回React的index.html。

方案2:以完整Node.js服务部署

若要保留完整Express服务器结构,需调整配置确保路由优先级:

  1. 修改server.js中路由顺序,先定义自定义接口,再托管静态文件:
const express = require("express");
const path = require("path");
const app = express();

// 优先处理自定义路由
app.get("/ping", function (req, res) {
  return res.send("pong");
});

// 再托管React静态文件
app.use(express.static(path.join(__dirname, "build")));

// 最后处理React单页路由的 fallback
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "build", "index.html"));
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});
  1. 根目录创建vercel.json指定部署配置:
{
  "buildCommand": "npm run build",
  "devCommand": "node server.js",
  "installCommand": "npm install",
  "functions": {
    "server.js": {
      "runtime": "@vercel/node@2.5.0"
    }
  }
}
  1. 检查Vercel控制台项目设置:确保构建命令为npm run build,输出目录为build。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:55:15