部署Express+Create React App后API路由返回index.html的问题
问题原因与解决方案
核心问题
Firebase Hosting 是静态文件托管服务,它不会自动运行你的 Express Node.js 服务器。你本地运行时是直接启动 Express 进程处理所有请求(先匹配 API 路由,再返回静态文件/SPA 入口),但部署到 Firebase 后,默认只会托管 build 文件夹里的静态资源,所有请求(包括 /api/test)都会被 Firebase 的 SPA 规则重定向到 index.html,这就是为什么你收到的是 HTML 而非 API 响应。
解决方案:结合 Firebase Functions 处理 API 路由
需要把 API 逻辑迁移到 Firebase Functions(Firebase 的无服务器函数服务),并配置 Hosting 的重写规则,让 /api 开头的请求转发到 Functions,其他请求仍返回前端静态文件。
步骤 1:初始化 Firebase Functions
- 安装 Firebase CLI:
npm install -g firebase-tools - 登录 Firebase:
firebase login - 在项目根目录初始化 Functions:
firebase init functions,选择 JavaScript/TypeScript,按提示完成初始化。
步骤 2:迁移 API 到 Functions
修改 functions/index.js,把你的 Express API 逻辑移到这里:
const functions = require("firebase-functions"); const express = require('express'); const app = express(); // 保留原有的解析中间件 app.use(express.urlencoded({ extended: true })); app.use(express.json()); // 你的 API 路由 app.post('/api/test', async (req, res) => { res.send("Hello world!"); }); // 导出为 Firebase HTTPS 函数 exports.app = functions.https.onRequest(app);
步骤 3:配置 Firebase Hosting 重写规则
修改项目根目录的 firebase.json,添加重写规则,将 /api 路径的请求转发到 Functions:
{ "hosting": { "public": "build", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "/api/**", "function": "app" }, { "source": "**", "destination": "/index.html" } ] } }
步骤 4:部署 Functions 和 Hosting
在项目根目录执行部署命令:
firebase deploy --only functions,hosting
关键注意事项
- 确保 Functions 依赖安装正确:进入
functions目录,执行npm install express(如果之前没装)。 - 检查 Functions 日志:如果 API 仍有问题,可通过 Firebase 控制台的「Functions > 日志」查看错误信息。
- CORS 问题:通过重写规则,前端和 API 会使用同一个域名,无需额外配置 CORS;如果直接调用 Functions 域名,需添加
cors中间件处理跨域。
内容的提问来源于stack exchange,提问作者Wiley Buchanan
相关产品推荐
相关产品推荐

