【问题标题】:Error "ReferenceError: request is not defined" from basic Firebase Functions run基本 Firebase 函数运行时出现错误“ReferenceError:请求未定义”
【发布时间】:2019-05-11 09:43:21
【问题描述】:

每当触发指向我的 Firebase 数据库的 onWrite() 时,都会尝试向 Slack 发送一个 webhook。关闭其他一些帖子/指南,我能够部署以下代码,但在执行时收到ReferenceError: Request is not defined 错误。我不知道如何解决未定义的请求。

const functions = require('firebase-functions');
const webhookURL = "https://hooks.slack.com/services/string/string";

exports.firstTest = functions.database.ref('first').onWrite( event => {
  return request.post(
    webhookURL,
    {json: {text: "Hello"}}
  );
});

【问题讨论】:

  • 默认的helloWorld函数也是抛出Request is not defined

标签: node.js firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

通过 URL 调用您的 Cloud Function 并发送回响应

通过执行exports.firstTest = functions.database.ref('first').onWrite(),您可以在实时数据库中创建、更新或删除数据时触发您的firstTest 云函数。它被称为后台触发器,见https://firebase.google.com/docs/functions/database-events?authuser=0

使用此触发器,一切都发生在后端,您无权访问请求(或响应)对象。 Cloud Function 没有任何前端的概念:例如,它可以由另一个写入数据库的后端进程触发。如果您想在前端检测云函数的结果(例如创建新节点),您必须设置一个侦听器来侦听这个新节点位置。


如果您想通过 HTTP 请求(可能来自您的前端,或来自另一个“API 使用者”)调用您的函数并接收对 HTTP 请求的响应,您需要使用另一种云函数,HTTP 云函数,参见https://firebase.google.com/docs/functions/http-events。另请参阅您可以直接调用的其他类型的云函数:Callable Cloud Functions


最后,请注意:



从您的 Cloud Function 调用外部 URL

如果您想从云函数调用外部 URL(例如您的问题中提到的 Slack webhook),您需要使用像 request-promise (https://github.com/request/request-promise) 这样的库。

请参阅How to fetch a URL with Google Cloud functions? request?Google Cloud functions call URL hosted on Google App Engine 了解一些示例

重要提示:请注意,您需要使用“Flame”或“Blaze”定价计划。

事实上,免费的“Spark”计划“只允许向 Google 拥有的服务发出出站网络请求”。请参阅https://firebase.google.com/pricing/(将鼠标悬停在“云功能”标题后面的问号上)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 2022-01-20
相关资源
最近更新 更多