首页 > 解决方案 > 自定义域 Firebase cloudfunctions API

问题描述

我已经使用 Firebase Cloud Functions 生产了一个 Express API,但我需要向它添加自定义域。我按照这些说明使用 Firebase 托管为 Cloud Functions 创建了一个自定义域,并最终得到以下内容firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint",
      "npm --prefix \"$RESOURCE_DIR\" run build"
    ],
    "source": "functions"
  },
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "ui": {
      "enabled": false
    }
  },
  "hosting": [{
    "site": "devbp",
    "target:":"devbp",
    "public": "public",
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      }
    ]
  }]
}

索引.ts

import { functions } from './utils/exports-converter';
import App from './web-api/configs/app';

export * from './functions';
export * from './backup/schedules';
export * from './firestore-triggers/credits/credits-triggers'
export * from './schedules/transactions/aggregations-schedules';


export const api = functions.runWith({
    memory: '1GB',
    timeoutSeconds: 300
}).https.onRequest(App.express);

出口转换器.ts

import * as express from "express";
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

export { express, functions, admin };

应用程序.ts

import * as cors from "cors";
import * as bodyParser from "body-parser";
import Routes from "./routes";
import { express } from "../../utils/exports-converter";

class App {
  public express: express.Application;
  constructor() {
    this.express = express();
    this.init();
    this.mountRoutes();
  }
  private init() {
    const corsOptions = { origin: true };
    this.express.use(cors(corsOptions));
    this.express.use(bodyParser.raw());
    this.express.use(bodyParser.json());
    this.express.use(bodyParser.urlencoded({ extended: true }));
  }
  private mountRoutes() {
    Routes.mount(this.express);
  }
}

问题是无法访问 api 内的端点,例如GET devbp.web.app/api/user?id=123返回Cannot GET /api/user. 此响应表明 Express 正在处理请求(如果没有,Hosting 将抛出 404 页面)但未按预期处理。

我相信我遗漏了一些东西,firebase.json因为如上所述,相同的 api 目前正在生产中。

有什么想法吗?

标签: javascriptfirebasegoogle-cloud-platformgoogle-cloud-functionsfirebase-hosting

解决方案


我不确定,如果我遵循逻辑,但是我new App在代码中看不到任何内容。如果我理解正确,如果您不创建新App对象,您将不会运行它的构造函数,因此不会创建快速应用程序。

我认为的第二件事:) 是,再次根据我的理解,当 http GET 请求调用 GET 请求时应该调用Express get()方法。

我发现本教程不是云功能,但逻辑相似。创建新实例 App 并调用 get 方法。


推荐阅读