我是nodeJs的初学者,但尝试连接到云服务器以通过firebase云通知发送通知
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from the ProjectSupporter Team");
});
exports.sendPushNotifications = functions.https.onRequest((req, res) => {
res.send("Attempting to send push notification...")
console.log("LOGGER --- Trying to send push message...")
// admin.message().sendToDevice()
var uid = 'Ky6h0BgpGDNMUyyBgE4ul99MzXk1'
return admin.database().ref('/users/' + uid).once('value', async snapshot => {
var user = snapshot.val();
console.log("User username: " + user.username + " fcmToken: " + user.fcmToken);
// See documentation on defining a message payload.
var message = {
notification: {
title: "Push Notification Title",
body: "Message Body..."
},
data: {
score: '850',
time: '2:45'
},
token: user.fcmToken
};
// Send a message to the device corresponding to the provided
// registration token.
try {
const response = await admin.messaging().send(message);
console.log('Successfully sent message:', response);
} catch(e) {
console.log('Error sending message:', error);
}
});
这是我收到的错误消息:
20:70错误解析错误:意外的令牌快照
✖1个问题(1个错误,0个警告)
npm ERR!代码ELIFECYCLE
npm ERR!错误1
npm ERR!函数@ lint:eslint .
npm ERR!退出状态1
npm ERR!
npm ERR!函数@ lint脚本失败。
npm ERR!这可能不是npm的问题。上面可能有额外的日志记录输出。
我的意见Brackets说第20,70行有一个错误。我无法弄清楚问题是什么。
这是一张图片: https://ibb.co/iBp17H
提前致谢!
答案 0 :(得分:0)
您收到的错误导致eslint
错误,如果您运行代码它会起作用,因为它是有效的javascript。
linter规则promise/always-return
要求你总是在一个承诺链内返回,即使是在最后.then
。所以只需返回一些内容或使用async/await
。
return admin.database().ref('/users/' + uid).once('value', snapshot => {
/*...*/
// Send a message to the device corresponding to the provided
// registration token.
return admin.messaging().send(message)
.then((response) => {
// promise/always-return
console.log('Successfully sent message:', response);
// Do something with response
return true; // To quiet linter.
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
使用async/await
(您需要首先转换代码)
Cloud Functions for Firebase Async Await style
return admin.database().ref('/users/' + uid).once('value', async snapshot => {
/*...*/
// Send a message to the device corresponding to the provided
// registration token.
try {
const response = await admin.messaging().send(message);
console.log('Successfully sent message:', response);
} catch(e) {
console.log('Error sending message:', error);
}
});