Firebase Functions配置自定义域名后无法正常调用的问题求助
问题分析与解决方案
你的核心问题是请求路径与Firebase Hosting的重写规则不匹配,导致请求被转发到React的index.html而非Firebase函数。以下是具体修复步骤:
问题根源
- 你配置的函数重写规则是
/app或/app/**,但实际API请求的路径是/api/createPromo,两者完全不匹配,请求会被第二个重写规则(**)转发到React页面,因此返回"You need to enable JavaScript to run this app." - 直接调用函数域名正常,说明函数本身逻辑无问题,仅路径映射配置错误。
修复方案(二选一)
方案一:统一使用/app作为API前缀
1. 修改firebase.json的重写规则
确保匹配所有/app开头的路径:
{ "hosting": { "public": "build", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "/app/**", "function": "app" }, { "source": "**", "destination": "/index.html" } ] } }
2. 修改React的API请求路径
将api.js中的请求URL改为/app/createPromo:
const response = await fetch(`https://xxxxxxxxx-dev.web.app/app/createPromo`, { method: 'POST', mode: 'cors', cache: 'no-cache', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token, }, body: JSON.stringify(body) });
3. 无需修改Express函数代码
Firebase会自动将/app前缀后的路径(即/createPromo)传递给Express,与你已定义的app.post('/createPromo')路由匹配。
方案二:使用/api作为API前缀(更符合常规命名)
1. 修改firebase.json的重写规则
{ "hosting": { "public": "build", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "/api/**", "function": "app" }, { "source": "**", "destination": "/index.html" } ] } }
2. 调整Express函数的路由前缀
将所有API路由统一添加/api前缀,推荐用路由分组的方式管理:
const express = require('express'); const app = express(); // etc... app.use(cors); app.use(cookieParser(MY_SECRET_VALUE)); app.use(validateFirebaseIdToken); // 创建API路由分组 const apiRouter = express.Router(); apiRouter.post('/createPromo', async (req: any, res: any) => { // 原有逻辑不变 res.json({ success: true, error: null, data }); }); // 挂载/api前缀 app.use('/api', apiRouter); exports.app = functions.https.onRequest(app);
3. 保持React的API请求路径不变
继续使用/api/createPromo即可。
最后部署验证
修改配置后,需要重新部署服务:
- 部署函数:
firebase deploy --only functions - 部署托管:
firebase deploy --only hosting
内容的提问来源于stack exchange,提问作者fabio
相关产品推荐
相关产品推荐

