ReferenceError:上下文未定义
2018-04-17
16605
我正在尝试使用 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');
});
});
});
我不知道错误出在哪里,有人能告诉我错误出在哪里吗,我该如何解决?
2个回答
将其更改为:
exports.sendNotification = functions.database.ref('notifications/{user_id}').onWrite((change,context) => {
const user_id = context.params.user_id;
});
onWrite
有两个参数
change
和
context
。您可以使用
context
访问通配符示例
user_id
。
更多信息请见此处:
Peter Haddad
2018-04-17
在@PeterHaddad 的帮助下,我成功解决了自己的问题。我阅读了他发布的链接,并更改了一些代码。这里是
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('notifications/{user_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have notification from: ', user_id);
if (!change.after.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');
});
});
});
2018-04-17