【问题标题】:Cannot read property 'val' of undefined无法读取未定义的属性“val”
【发布时间】:2019-12-23 15:42:51
【问题描述】:

我尝试学习如何使用 firebase 功能发送通知。所以我正在使用这个示例代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendAdminNotification = functions.database.ref('/message').onWrite(event => {
const news = event.data.val();
     const payload = {notification: {
         title: 'New news',
         body: `${news.title}`
         }
     };
return admin.messaging().sendToTopic("News",payload)
    .then(function(response){
         return console.log('Notification sent successfully:',response);
    }) 
    .catch(function(error){
         console.log('Notification sent failed:',error);
    });

});

但它给了我一个错误: Cannot read property 'val' of undefined 我一直在寻找解决方案,试过this,但还是不行……

任何建议将不胜感激。

【问题讨论】:

  • 尝试console.log(event) 找出问题所在。
  • 我怀疑您使用的是非常旧的教程或示例代码。我建议您阅读文档以获取有关 API 工作原理的最新描述。
  • 关于如何将代码迁移到 1.0 及更高版本的具体说明,请参阅firebase.google.com/docs/functions/…

标签: javascript firebase-realtime-database google-cloud-functions


【解决方案1】:

我认为您没有使用文档中指定的语法。

请参阅this 文档。

无论如何,正如我在上面链接的文档中看到的,您的代码应该是:

exports.sendAdminNotification = functions.database.ref('/message')
    .onWrite((change, context) => { 
        console.log(change);
        // Do something with change or context
    });

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2018-10-30
    • 2018-04-01
    • 2018-12-05
    • 2020-11-29
    • 1970-01-01
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    相关资源
    最近更新 更多