【问题标题】:Express routes and middleware with Firebase Cloud Functions使用 Firebase Cloud Functions 快速路由和中间件
【发布时间】:2019-02-18 12:08:36
【问题描述】:

问题

如何在 Firebase Cloud Functions 中使用 Express?

期望

使用我设置的任一 URL,我希望在控制台日志中看到 "Hello from Express on Firebase!"

为什么?我的理解是,"*" 表示所有请求的路由都应该response.send("Hello from Express on Firebase!");

app.get("*", (_request, response) => {
  response.send("Hello from Express on Firebase!");
});

问题

当我使用https://us-central1-myapp.cloudfunctions.net/helloWorld 时,我会在日志中得到预期的Hello from Firebase!。我还应该看到"Hello from Express on Firebase!"吗?

当我使用 https://us-central1-myapp.cloudfunctions.net/api 时,我得到一个 404 error

URL https://us-central1-myapp.cloudfunctions.net/api 是问题所在。请在下面的答案中查看原因。

代码

// Express
import express = require("express");
const app = express();
const cors = require("cors")({
  origin: "*"
});
app.use("*", cors);

// Firebase Functions SDK
import functions = require("firebase-functions");

app.get("*", (_request, response) => {
  response.send("Hello from Express on Firebase!");
});

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

exports.helloWorld = functions.https.onRequest((_request, response) => {
  response.send("Hello from Firebase!");
});

tl;博士

我希望完成的一个示例是here,但没有一个代码示例对我有用。我知道我得到了一个404 error

Express 文档 here 显示了一个类似的 HelloWorld 示例,但我对 Firebase 如何取代 app.listen(3000, () => console.log('Example app listening on port 3000!')) 感到困惑

cors 在我的示例代码中是否正常工作?虽然我得到了预期的响应和日志,但 Chrome 控制台警告:Cross-Origin Read Blocking (CORB) blocked cross-origin response https://appengine.google.com/_ah/lo....

我有一个 Slack 应用程序正在访问这些 URL(我也使用 chrome 访问它们)。最终,我想在我的 Google Cloud Functions 中使用 Botkit 中间件。我还没有掌握 Express app.use()app.get() 的正确设置

【问题讨论】:

  • 我看到firebase.jsonhosting 参数一起使用。我的示例项目没有使用托管,而且我认为它不需要。 Firebase Video 中的示例类似但又足够不同。

标签: express routing google-cloud-functions middleware


【解决方案1】:

回答

我犯了一个简单的错误,将/api 视为一个函数,而它实际上是路径的一部分。

通过使用带有尾随 / 的 URL

https://us-central1-myapp.cloudfunctions.net/api/

我现在正在使用 Express 路线和功能。

【讨论】: