【问题标题】:Sending notifications when button clicked errors当按钮点击错误时发送通知
【发布时间】:2018-11-01 03:50:13
【问题描述】:

我试图在有人单击“开始”按钮时通知我的用户,但我的 firebase 函数日志中不断出现一些错误。

未捕获的异常&

提供给 sendToDevice() 的注册令牌必须是非空字符串或非空数组

exports.observeGoing = functions.database.ref('/going/{postId}/{uid}').onCreate((snapshot,context) => {

var postId = context.params.postId;
var uid = context.params.uid;

console.log('User: ' + uid + ' is going to your activity');

return admin.database().ref('/users/' + uid).once('value', snapshot => {

var creatorOfPost = snapshot.val();

admin.database().ref('/users/' + uid).once('value', snapshot => {

  var userGoing = snapshot.val();

  var payload = {
    notification: {
      body: userGoing.usernames + " is going",
      sound: "default"
    }
  }

  admin.messaging().sendToDevice(creatorOfPost.fcmToken, payload)
  .then((response) => {
    console.log('Successfully send message:', response);
    return response
  })
  .catch((error) =>{
    console.log('Error sending message:', error);
  });
})
})
})

【问题讨论】:

  • 能否提供堆栈跟踪或那些错误?
  • 我不确定你的意思
  • 你能分享完整的错误信息吗?没有这个就很难判断出了什么问题
  • 记录creatorOfPost.fcmToken的值

标签: javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


【解决方案1】:

您收到该错误,因为 creatorOfPost.fcmToken 可以为空

根据firebase文档,admin.messaging.Messaging.sendToDevice()的第一个参数不能为空。

但在您的代码中,有两种可能违反此前提条件。

creatorOfPost.fcmToken 可以为空

在调用admin.messaging.Messaging.sendToDevice()之前只做空检查

creatorOfPost 可以为空

firebase.database.Reference.once()返回DataSnapshot,但并不代表总是有对应的文档。

所以,var creatorOfPost = snapshot.val(); 可以为空。

也许你可以这样检查:

return admin.database().ref('/users/' + uid).once('value', snapshot => {
  if (!snapshot.exists()) {
    return; // or do what you would like
  }

  var creatorOfPost = snapshot.val();
  // ...
  // ...
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多