How to send Firebase Cloud Messaging from a node server?

前端 未结 3 1981
名媛妹妹
名媛妹妹 2020-11-29 01:47

Is there any way to send notifications from FCM from a node.js server?

I haven\'t found anything about it inside documentation.

3条回答
  •  一整个雨季
    2020-11-29 02:18

    Sending messages through Firebase Cloud Messaging takes calling an HTTP end point as described in the documentation on sending downstream messages.

    Something as simple as this could do the trick:

    var request = require('request');
    
    function sendMessageToUser(deviceId, message) {
      request({
        url: 'https://fcm.googleapis.com/fcm/send',
        method: 'POST',
        headers: {
          'Content-Type' :' application/json',
          'Authorization': 'key=AI...8o'
        },
        body: JSON.stringify(
          { "data": {
            "message": message
          },
            "to" : deviceId
          }
        )
      }, function(error, response, body) {
        if (error) { 
          console.error(error, response, body); 
        }
        else if (response.statusCode >= 400) { 
          console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body); 
        }
        else {
          console.log('Done!')
        }
      });
    
    sendMessageToUser(
      "d7x...KJQ",
      { message: 'Hello puf'}
    );
    

    Update (April 2017): you can now also run code very similar to this in Cloud Functions for Firebase. See https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

提交回复
热议问题