【问题标题】:How to parse Json payload in Cloud Function triggered from Pub/sub如何解析从 Pub/sub 触发的 Cloud Function 中的 Json 有效负载
【发布时间】:2020-05-13 12:16:38
【问题描述】:

我是谷歌云功能和 Node Js 的新手,当我尝试解析 Json 有效负载时不断收到此错误

exports.processdata = (event, context) => {

  const pubsubMessage = event;

 var obj = JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString());
console.log(obj.temp);


};

错误

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
Function.Buffer.from

CLoud 函数在 Node.Js 版本 8 上运行

【问题讨论】:

  • 从错误中可以看出,您收到了您的第一个参数,我想您在代码示例中附加的“事件”应该是字符串、缓冲区、ArrayBuffer、数组或类似数组的基本上告诉你,你需要将它定义为其中之一。

标签: node.js google-cloud-functions google-cloud-pubsub


【解决方案1】:

您可以使用 .json 属性读取 json 有效负载,下面是完整代码

const functions = require('firebase-functions');
exports.processdata = functions.pubsub.topic('topic-np').onPublish((message) => {
  // [START readJson]
  // Get the `name` attribute of the PubSub message JSON body.
  let name = null;
  try {
    name = message.json.name;
  } catch (e) {
    console.error('PubSub message was not JSON', e);
  }

参考:https://firebase.google.com/docs/functions/pubsub-events

如果您正在测试在 Pub/Sub 上触发的云功能,请在主题中发布消息,然后通过云功能中的日志进行验证。

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2021-12-31
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2021-02-21
    • 2018-06-22
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多