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

Firebase+Express API本地与远程端点/api路径重复问题求助

解决Firebase Cloud Function + Express API路径重复/api的问题

问题核心是:Cloud Function的导出名称为api,加上Express路由中又使用了/api前缀,导致直接访问函数(本地/远程云域名)时URL出现重复的/api/api,而自定义域名通过Hosting转发正常。需要统一所有环境URL仅保留单次/api前缀,同时满足上层应用依赖/api开头路径的要求。

解决方案步骤

1. 修改Express路由代码(/functions/index.js)

移除Express路由中的/api前缀,让函数名称api作为URL中/api的来源,路由仅处理后续路径:

const functions = require('firebase-functions');
const express = require('express');

const app = express();

// 移除/api前缀,直接处理/echo路径
app.get('/echo', (req, res) => {
  res.status(200).json({
    message: req.query.message,
  });
});

// 若有多个/api开头的路由,统一移除/api前缀即可
// 示例:app.get('/user', ...) 对应原/api/user

exports.api = functions.https.onRequest(app);

如果路由较多,推荐使用Router管理更清晰:

const functions = require('firebase-functions');
const express = require('express');

const app = express();
const apiRouter = express.Router();

// Router中直接定义无/api前缀的路由
apiRouter.get('/echo', (req, res) => {
  res.status(200).json({
    message: req.query.message,
  });
});
apiRouter.get('/user', (req, res) => {
  res.status(200).json({ data: 'user info' });
});

// 将Router挂载到根路径
app.use('/', apiRouter);

exports.api = functions.https.onRequest(app);

2. 保留现有firebase.json配置

原有的Hosting重写规则无需修改,它会将自定义域名下的/api/**请求转发到api函数,并传递/**部分的路径给Express:

{
  "hosting": {
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api",
        "region": "us-central1"
      }
    ]
  },
  "functions": [
    {
      "source": "functions",
      "codebase": "default",
      "ignore": [
        "node_modules",
        ".git",
        "firebase-debug.log",
        "firebase-debug.*.log"
      ]
    }
  ]
}

验证各环境URL

修改后所有环境的URL均只需单次/api前缀,且返回预期结果:

  • 本地模拟器:http://localhost:5001/[my-project]/us-central1/api/echo/?message=Hello+World
  • 远程云函数域名:https://us-central1-[my-project].cloudfunctions.net/api/echo/?message=Hello+World
  • 自定义域名:https://www.[mydomain.tld]/api/echo/?message=Hello+World

所有请求均返回:

{"message":"Hello World"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:55:30