我想通过 firebase 云功能向设备发送推送通知。我正在编写node.js脚本
exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((event) => {
const sender_user_id = event.params.user_id;
const receiver_user_id = event.params.rec_user_id;
console.log('We have a notification from : '+ sender_user_id+ " | Receiced by " + receiver_user_id);
return;
});
在 firebase cloud 上部署功能后出现错误
TypeError: Cannot read property 'user_id' of undefined
完整的错误日志是:
TypeError: Cannot read property 'user_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:28:40)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
我得到了答复here https://stackoverflow.com/questions/49647170/firebase-functions-cannot-read-property-user-id-of-undefined
它工作正常,但是当我使用时
if(!event.data.val()){
return console.log('A Notification has been deleted from the database : ', sender_user_id);
}
Firebase 日志再次开始给我一条错误消息:
Cannot read property 'val' of undefined
如何消除这些错误?
提前致谢
关于val()
您需要执行以下操作:
exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((change,context) => {
const afterData=change.after.val();
});
既然你正在使用onWrite()
那么数据参数应该是change
,其中有before
and after
属性,其中每一个都是一个DataSnapshot
它有以下方法:
https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot
也供参考:
https://firebase.google.com/docs/reference/functions/functions.Change https://firebase.google.com/docs/reference/functions/functions.Change
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)