我正在尝试使用 node.js 和 firebase 函数创建一个 sendNotification 函数,但不幸的是我目前卡住了。我从未收到发件人的通知,当我查看 Firebase 函数日志时,我看到一条错误消息说
ReferenceError: context is not defined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:9:32)
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)
这是我的代码index.js代码
`const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('notifications/{user_id}').onWrite(event => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have notification from: ', user_id);
if (!event.val()) {
return console.log('A Notification has been deleted from the database: ', notification_id);
}
const fromUser = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return fromUser.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: "Friend Request",
body: "You've received a Friend Request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id , payload).then(response => {
console.log('This was the notification feature');
});
});
});
我不知道这里的错误在哪里,谁能告诉我错误在哪里,我该如何解决?
最佳答案
改成这样:
exports.sendNotification = functions.database.ref('notifications/{user_id}').onWrite((change,context) => {
const user_id = context.params.user_id;
});
onWrite
有两个参数change
和context
。您使用 context
访问通配符示例 user_id
。
更多信息在这里:
关于javascript - 引用错误 : context is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870429/