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

Vite React部署Firebase Hosting后调用Cloud Functions v2遇404问题

问题分析与解决方案

核心原因:Cloud Functions v2 与 v1 重写规则的差异

Firebase Hosting 对 v2 函数的重写逻辑和 v1 不同,你遇到404大概率是区域未指定、函数ID错误,或者本地代理与线上路由不匹配导致的。

1. 先搞对 Function ID

你看到的functions-someid-ey不是v2函数的ID,正确的函数ID是你代码里定义的导出名(比如exports.api = onRequest(...)里的api),或者去Firebase控制台的Cloud Functions页面看完整ID——格式是projects/[你的项目ID]/locations/europe-west3/functions/[函数名]。

2. 修正 firebase.json 的 rewrites 配置

必须明确指定区域和函数ID,同时处理路由前缀的匹配:

{
  "hosting": {
    "public": "dist", // 对应Vite打包后的输出目录
    "rewrites": [
      {
        "source": "/functions/**",
        "function": {
          "functionId": "api", // 这里填你的函数名,或者完整的项目+区域+函数ID路径
          "region": "europe-west3"
        }
      },
      {
        "source": "**",
        "destination": "/index.html" // React单页应用的兜底路由,不能少
      }
    ]
  }
}

注意:如果你的Express应用里已经给路由加了/functions前缀(比如app.use('/functions', router)),那要把source改成/**,或者删掉Express里的/functions前缀——不然线上请求/functions/someMethod1会被转发到函数的/functions/someMethod1,而你的函数可能只处理/someMethod1,直接404。

3. 对齐本地代理与线上路由

本地Vite的代理配置大概是这样的:

export default defineConfig({
  server: {
    proxy: {
      '/functions': {
        target: 'https://functions-someid-ey.a.run.app',
        changeOrigin: true
      }
    }
  }
})

这时候本地请求/functions/someMethod1会被转发到函数的/someMethod1,但如果线上重写后,你没调整Express路由,就会出现路径不匹配的问题——确保函数里的路由是/someMethod1,而不是/functions/someMethod1。

4. 先验证函数本身是否正常

直接访问https://functions-someid-ey.a.run.app/someMethod1,如果这里也返回404,那问题出在你的Express函数路由配置,和Hosting重写没关系,先把函数本身调通。

5. 部署后清缓存

Firebase Hosting有缓存机制,部署完可以跑firebase hosting:clear-cache命令清缓存,或者去控制台手动刷新,避免旧配置干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:30:18