如何从节点服务器发送 Firebase 云消息传递? [英] How to send Firebase Cloud Messaging from a node server?

查看:37
本文介绍了如何从节点服务器发送 Firebase 云消息传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 node.js 服务器发送来自 FCM 的通知?

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

我在文档中没有找到任何关于它的内容.

I haven't found anything about it inside documentation.

推荐答案

通过 Firebase Cloud Messaging 发送消息需要调用 HTTP 端点,如 关于发送下游消息的文档.

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+'
'+body); 
    }
    else {
      console.log('Done!')
    }
  });

sendMessageToUser(
  "d7x...KJQ",
  { message: 'Hello puf'}
);

更新(2017 年 4 月):您现在还可以在 Cloud Functions for Firebase 中运行与此非常相似的代码.请参阅 https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

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

这篇关于如何从节点服务器发送 Firebase 云消息传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆