如何从自定义域提供 Firebase 功能?

时间:2021-04-11 00:18:59

标签: firebase google-cloud-functions firebase-hosting

我有一个网站,我已经使用 Google 域在 Firebase 托管上运行该网站。我现在想显示对我的 firebase 函数的所有调用都是通过 api.mydomain.com 之类的 url 进行的,而不是默认的 firebase 域。我怎么可能做到这一点?

我在 hosting cloud functions 上阅读了 firebase 教程,还遇到了 this article 创建多个网站的问题。那么有人可以告诉我如何设置工作流程,以便我的网站仍在 mydomain.com 上运行,但我的 API 现在正在通过 api.mydomain.com 调用?

的目标名称是什么

如果可能,我希望所有请求都显示为对 api.mydomain.com 的请求,而不是对 api.mydomain.com/endpoint 的请求 - 这样也可以对公开的端点隐藏

抱歉,我是新手。

1 个答案:

答案 0 :(得分:0)

假设您的主项目的 ID 为 example-app。要将请求作为 api.mydomain.com 提供服务,您必须使用利用 express(或其他一些类似的路由处理程序)的云函数。

  1. 使用 Firebase CLI 为您的项目创建辅助站点(ID 为 example-app-apiexample-api 等)
firebase hosting:sites:create example-app-api
  1. 将您的托管目标连接到您的资源
firebase target:apply hosting app example-app
firebase target:apply hosting api example-app-api
  1. 修改您的 firebase.json 文件以适合上述目标。
{
  "hosting": [
    {
      // app is linked to example-app, served as mydomain.com
      "target": "app",

      // contents of this folder are deployed to the site "example-app"
      "public": "public",

      // ... other settings ...
    },
    {
      // api is linked to example-app-api, served as api.mydomain.com
      "target": "api",

      // Contents of this folder are deployed to the site "example-app-api"
      // Any file here will be returned instead of calling your Cloud Function.
      // Recommended contents:
      //   - favicon.ico        (website icon for bookmarks, links, etc)
      //   - robots.txt         (instructions for bots and scrapers)
      // Optional contents:
      //   - service-worker.js  (empty file, used to prevent triggering cloud function)
      //   - humans.txt         (details about who you/your company are & how to report bugs)
      "public": "api-static-resources",  

      // ... other settings ...

      "rewrites": [
        {
          // redirect all calls to the function called "api"
          "source": "**",
          "function": "api"
        }
      ]
    }
  ]
}
  1. 使用 Firebase CLI 部署 api 托管配置
firebase deploy --only hosting:api
  1. 为您的项目打开 Hosting Settings,点击 example-app-api 的“查看”,然后点击 these instructions 后面的“自定义域”。

  2. 您现在应该可以通过在 api.mydomain.com 处调用 Cloud 函数来触发它。

api.mydomain.com/getPost?id=someId
api.mydomain.com/favicon.ico
api.mydomain.com/robots.txt
相关问题