使用Firebase云功能发送通知有困难吗?

时间:2018-12-01 07:52:51

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

我想进行一个云功能,因此向iOS应用的所有用户发送通知。作为第一个测试,我只想向一个用户发送通知。

下面是相关代码。当我运行它时,它会显示在浏览器中:

Error: could not handle the request

有人可以看到我在哪里做错了吗?

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.cert({
    projectId: 'myAppID',
    clientEmail: 'firebase-adminsdk-gotiq@edo-press-japan.iam.gserviceaccount.com',
    privateKey: '-----BEGIN PRIVATE KEY-----\n........=\n-----END PRIVATE KEY-----\n'
  }),
  databaseURL: 'https://myApp.firebaseio.com'
});

let registrationToken = "112233..aabbcc...7788";
exports.sendNotification = functions.https.onRequest((req, res) => {
    var payload = {
        data:{
          title: "ELR",
          body: "The world has been messed up."
        },
        token: registrationToken
    };

    admin.messaging().send(payload)
    .then((response) => {
        console.log("Successfully sent message: ", response);
        response.send("Hello from Firebase! - ALL IS GOOD !!");
        //return true;
    })
    .catch((error) => {
        console.log("Error sending message: ", error);
        response.send("Hello from Firebase! - FAILED !!");
        //return false;
    })
})

1 个答案:

答案 0 :(得分:0)

您的代码中的变量名中有错别字:一方面使用res,另一方面使用response。您应该对其进行如下修改:

exports.sendNotification = functions.https.onRequest((req, res) => {
    var payload = {
        data:{
          title: "ELR",
          body: "The world has been messed up."
        },
        token: registrationToken
    };

    admin.messaging().send(payload)
    .then((response) => {
        console.log("Successfully sent message: ", response);
        res.send("Hello from Firebase! - ALL IS GOOD !!");  // <-- here use res and not response
    })
    .catch((error) => {
        console.log("Error sending message: ", error);
        res.status(500).send("Hello from Firebase! - FAILED !!"); // <-- here, use res and add status(500)
    })
})

此外,请注意,正如道格的官方视频系列所建议的那样,我已将最后一行更改为res.status(500).send(),请参见https://www.youtube.com/watch?v=7IkUgCLr5oAhttps://www.youtube.com/watch?v=7IkUgCLr5oA

enter image description here