【问题标题】:Adding custom parameters/queries/headers to a Google Cloud function向 Google Cloud 函数添加自定义参数/查询/标头
【发布时间】:2020-02-06 16:45:35
【问题描述】:

我基本上想知道是否可以让 https Google Cloud 函数根据我作为参数传递给它的内容以不同方式执行(就像任何带有参数的普通函数一样)。可能在 URL 中使用简单的查询或任何其他有效的方法。

作为一个例子,看看任何教程中的基本启动函数:

exports.helloWorld = functions.https.onRequest((req, res) => {
  res.status(200).send('Hello, World!');
});

我想做这样的事情:

exports.helloWorld = functions.https.onRequest((req, res) => {
  let name = req.query;
  res.status(200).send(`Hello, ${name}!`);
});

我希望这是有道理的。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js google-cloud-platform google-cloud-functions


    【解决方案1】:

    您好,由于 HTTPS 云函数是 POST 请求,您可以在请求正文中传递任何类型的参数。

    示例:
    云功能:

    exports.helloWorld = functions.https.onRequest((req, res) => {
      let name = req.body.name;
      res.status(200).send(`Hello, {name}!`);
    });
    

    客户:

    fetch('https://firebase.url/helloWorld ', {
        method: 'post',
        body: {name: "Name"},
      }).then(function(response) {
        return response.json();
      }).then(function(data) {
        console.log(data)
      });
    

    您可以在这里使用任何请求方法。

    希望这会有所帮助。

    【讨论】:

    • 您还需要添加 '$' 以在 JS 字符串中插入变量:res.status(200).send(`Hello, ${name}!`);
    • 我尝试使用 Cloud Scheduler 执行此操作,方法是将 {name: "Name"} 插入到那里的作业正文中。但这会返回 undefined 。对此有何建议?
    • 最终你需要像这样添加它:{"name": "Name"}
    • 谢谢。现在明白了。我还必须在我的代码中将其解析为 JSON,因为它只返回一个字符串。
    【解决方案2】:

    确实可以将各种参数传递给您的 Cloud Function。

    这是一个简单的示例供您参考:

    index.js

    exports.helloWorld = (req, res) => {
      let name = req.body.name || req.query.name;
      res.status(200).send(`Hello ${name}!`);
    };
    

    我可以通过为触发该功能而提供的 URL 调用它,方法是在该 URL 后面附加/?name=<desired-name>:

    https://<function-region>-<project-name>.cloudfunctions.net/<function-name>/?name=Christiaan
    

    或者,也可以使用 curl 调用它:

    curl --data "name=Christiaan" https://<functions-region>-<project-name>.cloudfunctions.net/<function-name>
    

    输出

    Hello Christiaan!
    

    【讨论】:

    • 这个答案解释得更好。谢谢。
    猜你喜欢
    • 2015-12-18
    • 2012-04-23
    • 2020-03-11
    • 2022-01-01
    • 1970-01-01
    • 2013-09-14
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多