NodeJS 如何在firebase中发送HTTP请求以发送通知?

ukqbszuj  于 2022-12-18  发布在  Node.js
关注(0)|答案(2)|浏览(209)

要发送通知,您需要发送以下HTTP请求:

POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=YOUR_SERVER_KEY

{
  "notification": {
    "title": "New chat message!",
    "body": "There is a new message in FriendlyChat",
    "icon": "/images/profile_placeholder.png",
    "click_action": "http://localhost:5000"
  },
  "to":"YOUR_DEVICE_TOKEN"
}

我该怎么做呢?

trnvg8h3

trnvg8h31#

如果您使用的是Node.JS,我建议您查看Firebase的Node.JSSDK文档,而不是手动发送HTTP请求。
如果仍然希望使用普通HTTP方法,可以使用request npm模块

$ npm install request

然后在你的代码中

const request = require('request');

request({
  url: 'https://fcm.googleapis.com/fcm/send',
  method: 'POST',
  headers: {
    "Content-Type": "application/json",
    "Authorization": ['key', yourServerKey].join('=')
  },
  json: {
    to: clientFirebaseToken,
    notification: {
      title: "Notification Title",
      body: "This is a neat little notification, right ?"
    }
  });

编辑

从他们的GitHub
截至2020年2月11日,该请求已被完全否决。预计不会有新的更改。事实上,一段时间以来没有任何更改。
如果使用axios

axios({
  method: 'post',
  url: 'https://fcm.googleapis.com/fcm/send',
  headers: {
    "Content-Type": "application/json",
    "Authorization": ['key', yourServerKey].join('=')
  },
  params: {
    to: clientFirebaseToken,
    notification: {
      title: "Notification Title",
      body: "Neat indeed !"
    }
  }
})

6l7fqoea

6l7fqoea2#

如果您正在使用React JS/ React Native,使用Axios包可以非常容易地完成,示例代码如下,首先,您必须注册firebase云消息传递以获取授权密钥

axios.post(
          'https://fcm.googleapis.com/fcm/send',
          {
            data: {},
            notification: {
              title: "Sample text1",
              body: "Sample text2",
              image: "Sample text3",
            },
            to: '/topics/TopicName',
          },
          {
            headers: {
              Authorization:
                'key=Authorization key from firebase',
              
            },
          },
        )
        .then(Response => {
          console.log(Response.data);
        });

相关问题