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函数:
- 在项目根目录新建
api文件夹,创建api/ping.js文件,写入接口逻辑:
module.exports = (req, res) => { res.send("pong"); };
- 根目录创建
vercel.json,添加重写规则:
{ "rewrites": [ { "source": "/ping", "destination": "/api/ping" }, { "source": "/(.*)", "destination": "/index.html" } ] }
此配置会将/ping请求转发到Serverless函数处理,其余请求返回React的index.html。
方案2:以完整Node.js服务部署
若要保留完整Express服务器结构,需调整配置确保路由优先级:
- 修改
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}`); });
- 根目录创建
vercel.json指定部署配置:
{ "buildCommand": "npm run build", "devCommand": "node server.js", "installCommand": "npm install", "functions": { "server.js": { "runtime": "@vercel/node@2.5.0" } } }
- 检查Vercel控制台项目设置:确保构建命令为
npm run build,输出目录为build。
内容的提问来源于stack exchange,提问作者maximosis
相关产品推荐
相关产品推荐

