问题描述
我已经有使用Firebase Cloud Functions的生产中的Express API,但是我需要向其中添加自定义域。我跟随these instructions使用Firebase Hosting为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"
}
]
}]
}
index.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);
exports-converter.ts
import * as express from "express";
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
export { express,functions,admin };
app.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正在处理请求(如果没有,则托管将抛出404页),但未达到预期的效果。
我相信我的firebase.json
中缺少某些内容,因为目前正在生产与上述相同的api。
有什么想法吗?
解决方法
根据documentation(以及here)托管语法是:
"hosting": {
...
}
在显示的firebase.json
中,您有[{ ... }]
。
尝试删除方括号。
我不确定是否遵循逻辑,但是在代码中的任何地方都看不到任何new App
。如果我正确理解如果不创建新的App
对象,则不会运行它的构造函数,因此将不会创建express应用。
我认为第二件事是:)再次,根据我的理解,http GET请求调用GET请求时应该调用Express get()方法。
我发现这个tutorial不是云功能,但是逻辑相似。创建新实例应用程序并调用get方法。