Node js with Firebase (FCM) push notification

2019-07-22 14:09发布

问题:

I'm developing REST api using node js and there is a rest endpoint to send firebase push notification. My code is below,

const bodyParser = require('body-parser');
var cors = require('cors');
var FCM = require('fcm-node');
//var FCM = require('fcm-push');

router.post('/pushmessage', function (req, res) {

    var serverKey = 'server key taken from firebase site cloud messaging tab';
    var fcm = new FCM(serverKey);
    var reqObj = req.body;
    var token = reqObj.userToken;
    console.log("Token Value  :   " + token);
    var message = {
        to: token,
        collapse_key: 'xxxxxxxxxxxxxx',
        notification: {title: 'hello', body: 'test'},
        data: {my_key: 'my value', contents: "abcv/"}
    };
    fcm.send(message, function (err, response) {
        if (err) {
            res.json({status: 0, message: err});
            console.log("error : "+err);
        } else {
            console.log("MESSAGE SEND");
            res.json({status: 1, message: response});
        }
    })
});

Generated push id from android client app hitting to this endpoint correctly. But always it gives error {"multicast_id":6340735554735214,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]} after request got hit. Please anyone can help me? This question is previously asked in here.

But this is not working for me. Also I tried this and this.

But no any progress. Please help.

回答1:

It's not mandatory to depend only on GCM, today there are many packages are available for sending pushNotification.

Two node packages are listed below.

  • fcm-call - you can find documentation from https://www.npmjs.com/package/fcm-call
  • fcm-node - you can find documentation from https://www.npmjs.com/package/fcm-node/

Use of fcm-call,

let FCM = require('fcm-call');
const serverKey = '<Your Server Key>'; 
const referenceKey = '<Your reference key>'; //Device Key
let title = '<Your notification title here.>';
let message = '<Your message here>';

FCM.FCM(serverKey, referenceKey, title, message);

This small snippet will send PushNotification to your dedicated device within 2-3 seconds.

Happy Notification.