Abdul Shadaab
Abdul Shadaab

Reputation: 41

how to i send HTTP request for sending notification in firebase?

To send a notification, you'll need to send the following HTTP request:

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"
}

how can I do this??

Upvotes: 0

Views: 4530

Answers (2)

Soumik Chakraborty
Soumik Chakraborty

Reputation: 253

If you are using React JS/ React Native, using the Axios package it can be done very easily, the sample code is below, first, you have to register for firebase cloud messaging to get the authorization key

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);
        });

Upvotes: 0

Mouradif
Mouradif

Reputation: 2694

If you're using Node.JS, I suggest you look at the documentation for Firebase's Node.JS SDK instead of manually sending HTTP requests. There's the official documentation or this nice tutorial

If you still want to go for the plain HTTP method, you can use the request npm module

$ npm install request

then in your code :

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 ?"
    }
  });

Edit

From their GitHub

As of Feb 11th 2020, request is fully deprecated. No new changes are expected to land. In fact, none have landed for some time.

If you use 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 !"
    }
  }
})

Upvotes: 2

Related Questions