因此,我尝试使用Firebase云消息传递向我的应用发送推送通知。然而,由于一些奇怪的原因,似乎连续失败。我正在使用onCreate方法来侦听在特定路径下创建节点。它是从UID
方法收集的信息中获取onCreate
但是当我尝试从其他节点获取用户信息以获取fcmToken时,我可以发送通知。它总是说未定义。
我的index.js看起来像这样:
//listen for reply notification and then trigger a push notification
exports.observeNotification = functions.database.ref('/notifications/{uid}/{commentId}/')
.onCreate(event => {
// Grab the current value of what was written to the Realtime Database.
//const notification = event.data.val();
console.log('User ID is: ', event.params.uid);
console.log('Comment ID Is: ', event.params.commentId);
return admin.database().ref('/users/' + event.params.uid).once('value', snapshot => {
var userWeAreSendingTo = snapshot
console.log('User ID is: ', userWeAreSendingTo);
console.log('FCM Token of that user is: ', userWeAreSendingTo.fcmToken);
var payload = {
notification: {
title: "",
body: snapshot.content
}
};
admin.messaging().sendToDevice(userWeAreSendingTo.fcmToken, payload)
.then((res) => {
// Response is a message ID string.
console.log('Successfully sent message:', res);
return true
})
.catch((error) => {
console.log('Error sending message:', error);
return true
})
})
})
这是我数据库中用户节点下的子节点的快照。
"9mzAHeX3lcdzriPdC4TfbRTkaUm2" : {
"fcmToken" : "coC8uorosgc:APA91bGur2vvH4fwIProh87pUzVw0jYTOOFW3KfqWRVk4WdX0x8M1iBFwg28wM3tFyB5iRrowTWCZ_45oGwo0_7BFD6YvULE30NNZXxvE2O2XLjlLd_fqYwMfkndOqSUem2HqO-qvNcZ",
"profilePic" : "https://firebasestorage.googleapis.com/v0/b/eventful-3d558.appspot.com/o/profile_images%2F832F8156-C14A-4EF3-86EB-D8F4CFC784E5.PNG?alt=media&token=b9d11ea1-8cb3-4d0f-b111-b0baf567ac7b",
"username" : "lol123"
}
控制台日志的屏幕截图