【问题标题】:How to send a firebase cloud message in typescript?如何在打字稿中发送 Firebase 云消息?
【发布时间】:2020-08-07 13:07:17
【问题描述】:

我想知道如何通过我的 firebase 函数后端发送 firebase 云消息。有效载荷似乎存在问题。我想知道如何解决这个问题。有效载荷是否需要接口?提前致谢!

错误

Error sending message: { Error: Invalid JSON payload received. Unknown name "message" at 'message': Cannot find field.  
at FirebaseMessagingError.FirebaseError [as constructor] (/home/ubuntu/environment/****/functions/node_modules/firebase-admin/lib/utils/error.js:42:28)

通知功能(更新工作代码)

async function notification(
  notificationType: string,
  registrationToken: string,
  objectText: string
) {
  const matchesRef = db.collection("notifications");
  const notificationObject = await matchesRef.doc(notificationType).get();

  if (notificationObject.exists) {
    const tokenMessage: admin.messaging.Message = {
      token: registrationToken,
      notification: {
        title: notificationObject.data()!.title,
        body: notificationObject.data()!.body
      },
      data: {
        click_action: "FLUTTER_NOTIFICATION_CLICK",
        title: notificationObject.data()!.title,
        body: notificationObject.data()!.body
      },
      android: {
        priority: "high"
      },
      apns: {
        headers: {
          "apns-priority": "5"
        }
      }
    };
    admin
      .messaging()
      .send(tokenMessage)
      .then((response: string) => {
        // Response is a message ID string.
        logMe(`Successfully sent message: ${response}`);
        return response;
      })
      .catch((error: string) => {
        console.log("Error sending message:", error);
      });
  }
  return false;
}

【问题讨论】:

    标签: typescript firebase firebase-cloud-messaging


    【解决方案1】:

    如果您尝试使用 TokenMessage 结构,您可以从链接的 API 文档中看到它不包含 message 属性。去掉外层和顶层多余的token字段:

        const message = {
            token: registrationToken,
            notification: {
              title: notificationObject.data()!.title,
              body: notificationObject.data()!.body
            },
            data: {
              click_action: "FLUTTER_NOTIFICATION_CLICK",
              title: notificationObject.data()!.title,
              body: notificationObject.data()!.body
            },
            android: {
              priority: "high"
            },
            apns: {
              headers: {
                "apns-priority": "5"
              }
            }
        };
    

    【讨论】:

    • 谢谢,您的回答让我找到了解决方案。有必要将消息定义为: const tokenMessage: admin.messaging.Message = { token: registrationToken, notification: {...
    猜你喜欢
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2021-07-06
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多