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

1 javascript firebase google-cloud-functions firebase-cloud-messaging

我正在尝试使用Firebase云功能将通知发送到点半径范围内的设备。我可以获取圈子中设备的ID,但无法获取令牌,如使用console.log(token)打印,令牌为null。

     const getdevicetokenpromise = db.ref('/DriversAvailable/{key}/token').once('value');
     console.log(key); //this value is right

    return getdevicetokenpromise.then(result => {
        console.log(result.val());   //this value is null, this is the problem
        var token = result.val();
        const payload = {
            notification: {
                title: 'title',
                body: 'hey, well done dude',
                icon: 'default'

                }
            };



        return admin.messaging().sendToDevice(token, payload)
        .then((response)=> {
        return console.log("Successfully sent message:", response);
        })
        .catch((error) =>{
        console.log("Error sending message:", error);
        });

    });
Run Code Online (Sandbox Code Playgroud)

我已经尝试了关于stackoverflow的大多数建议,但找不到解决方案。谢谢。

Dou*_*son 5

似乎您假设应该将value key插入此字符串中:

 const getdevicetokenpromise = db.ref('/DriversAvailable/{key}/token').once('value');
Run Code Online (Sandbox Code Playgroud)

但是,那不是它的工作方式。您实际上是在查询该确切的字符串,而key没有插入。我想您打算将JavaScript语法用于变量插值,并在字符串周围使用反引号,并使用$ {}来分隔变量:

 const getdevicetokenpromise = db.ref(`/DriversAvailable/${key}/token`).once('value');
Run Code Online (Sandbox Code Playgroud)