![](/img/trans.png)
[英]Firebase Cloud Function error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array
[英]Firebase Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array
我想在使用Firebase云消息传递给朋友的朋友请求时向用户发送通知,但是当发送请求时,它将在Firebase功能日志中返回此错误
错误:提供给sendToDevice()的注册令牌必须是非空字符串或非空数组。 在FirebaseMessagingError.Error处(本机)在FirebaseMessagingError.FirebaseError处(作为构造函数)(/ user_code / node_modules / firebase-admin / lib / utils / error.js:39:28)
这是我正在使用的Java脚本代码
'use strict' const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sendNotification = functions.database.ref('/Notifications/{user_id}/{notification_id}').onWrite((change, context) => { const user_id = context.params.user_id; const notification_id = context.params.notification_id; console.log('We Have A Notification for :', user_id); if (!change.after.val()){ return console.log("A Notification Has Been Deleted From The Database: ", notification_id) } const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value'); return deviceToken.then(result => { const token_id = result.val(); const payload = { notification: { title: "Friend Request", body: "You just got a new friend request", icon: "default" } }; return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{ console.log('this is the notification') }); }); });
听起来token_id
为null
或空字符串。 这很可能是因为/Notifications/${user_id}/${notification_id}
在您的数据库中不存在,例如,当目标用户没有令牌时。
为避免出现错误消息,只需在使用快照值之前检查快照是否存在:
const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
return deviceToken.then(result => {
if (!result.exists() || result.val() === "") return false;
const token_id = result.val();
const payload = {
notification: {
title: "Friend Request",
body: "You just got a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{
console.log('this is the notification')
});
});
经过许多小时的浪费后,我发现了什么地方出了问题。 现在的问题是我指向了错误的道路。 这行代码就是问题
const deviceToken = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
应该是这个
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.