【问题标题】:Firebase Cloud Messaging: event is not definedFirebase 云消息传递:未定义事件
【发布时间】:2018-08-01 15:57:41
【问题描述】:

我在使用 Firebase 云消息传递通知时遇到了问题。当我想发送好友请求时,其他客户端没有收到通知。 Firebase 函数日志显示:

ReferenceError: event is not defined
    at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:14:8)
    at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:109:23)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:139:20)
    at /var/tmp/worker/worker.js:728:24
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这里是 JavaScript 代码:

'use strict'

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

exports.sendNotification = functions.database.ref('/Notifications/{receiver_id}/{notification_id}').onWrite((change,context) => {
 const receiver_id = context.params.receiver_id;

 const notification_id = context.params.notification_id;

console.log('We have a notification to send to: ', receiver_id);

  if (!event.data.val) {
    return console.log('A notification has been deleted from database: ', notification_id);
  }

  const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');

  return deviceToken.then(result => {
    const token_id = result.val();

    const payload = {
      notification:
      {
        title: "Friend Request",
        body: "you have received a new friend request",
        icon: "default"
      }
    };

    return admin.messaging().sendToDevice(token_id, payload).then(response => {
      console.log('This was the notification feature.');
    });
  });

});

【问题讨论】:

  • 这个event,就在这里,event.data.val,没有定义。在您的上层范围内,您甚至没有对 event 的引用。你期望event 是什么?您希望它来自哪里?

标签: javascript firebase firebase-cloud-messaging google-cloud-functions


【解决方案1】:

改变这个:

if (!event.data.val) {
return console.log('A notification has been deleted from database: ', notification_id);
 }

进入这个:

if (!change.after.val()) {
return console.log('A notification has been deleted from database: ', notification_id);
 }

change 对象有两个属性afterbefore,每个属性都是DataSnapshot,与admin.database.DataSnapshot 中可用的方法相同。

另外val() 是一个方法而不是一个属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多