Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firebase实时数据库fcm消息发送问题_Javascript_Node.js_Firebase_Firebase Cloud Messaging_Google Cloud Functions - Fatal编程技术网

Javascript Firebase实时数据库fcm消息发送问题

Javascript Firebase实时数据库fcm消息发送问题,javascript,node.js,firebase,firebase-cloud-messaging,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Cloud Messaging,Google Cloud Functions,我是Firebase的新手,我一直在尝试制作一个发送/接收通知的android应用程序。几周前,这段代码对我来说还不错,但现在它显示了错误,尽管我没有做任何更改 代码: 'use strict' const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.pu

我是Firebase的新手,我一直在尝试制作一个发送/接收通知的android应用程序。几周前,这段代码对我来说还不错,但现在它显示了错误,尽管我没有做任何更改

代码:

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.database.ref(`/notification/{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 to send',user_id);

    const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
    const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);

    return Promise.all([deviceToken,senderId]).then(results =>{
        const tokensSnapshot = results[0];
        const sender = results[1];

        console.log("Device Token ID: ",tokensSnapshot.val());
        console.log("Sender ID: ",sender);

        const payload ={
            notification: {
                title: "New message",
                body: "hello",
                icon: "ic_launcher_round"
            }
        };
        return admin.messaging().sendToDevice(tokensSnapshot.val(),payload).then(response =>{
            response.results.forEach((result,index) =>{
                const error = result.error;
                if(error){
                    console.error('Failure sending notification to device',tokensSnapshot.val(),error);
                }
                else{
                    console.log('Notification sent to : ',tokensSnapshot.val());
                }
            });
            return null;
        });
    });
});
tokensSnapshot.val is not a function
    at Promise.all.then.results (/user_code/index.js:24:50)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
错误:

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.pushNotification = functions.database.ref(`/notification/{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 to send',user_id);

    const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
    const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);

    return Promise.all([deviceToken,senderId]).then(results =>{
        const tokensSnapshot = results[0];
        const sender = results[1];

        console.log("Device Token ID: ",tokensSnapshot.val());
        console.log("Sender ID: ",sender);

        const payload ={
            notification: {
                title: "New message",
                body: "hello",
                icon: "ic_launcher_round"
            }
        };
        return admin.messaging().sendToDevice(tokensSnapshot.val(),payload).then(response =>{
            response.results.forEach((result,index) =>{
                const error = result.error;
                if(error){
                    console.error('Failure sending notification to device',tokensSnapshot.val(),error);
                }
                else{
                    console.log('Notification sent to : ',tokensSnapshot.val());
                }
            });
            return null;
        });
    });
});
tokensSnapshot.val is not a function
    at Promise.all.then.results (/user_code/index.js:24:50)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

我根本不希望您的代码能够工作。看看你在这里做什么:

const deviceToken = admin.database().ref(`/users/${user_id}/tokenId`);
const senderId = admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`);

return Promise.all([deviceToken,senderId]).then(results => { ... })
deviceToken
senderId
是数据库引用。它们只是指向数据库中的位置。但是,您将它们传递给
Promise.all()
,就好像它们是承诺一样。这绝对不是承诺。这意味着回调中的
results
将不包含数据快照对象

您需要查询数据库中的值,并掌握这些查询的承诺。注意使用
once()
查询引用:

const deviceToken =
    admin.database().ref(`/users/${user_id}/tokenId`).once('value');
const senderId =
    admin.database().ref(`/notification/${user_id}/${notification_id}/fromuser`).once('value');
once()
返回一个承诺,该承诺将通过引用位置的数据快照进行解析


之后,代码中还有更多错误需要解决。特别是,您永远不会调用
sender
上的
val()
来获取您试图查询的原始数据。而且在这之后,您再也不会在任何地方使用发送者值(因此,查询它似乎毫无意义)。

非常感谢您的回答。我终于明白我做错了什么。