0

I couldn't run the function why? my goal is to send token to this function ,but I can't get into the function.

there is no output in firebase function console (console.log("Is it Working ? ") console.log("ReqBody : "+req)

where am i doing wrong ?

exports.sendNotifications = functions.https.onRequest((req, res) => {
  if (req.method !== 'POST') {
    return res.status(500).json({ message: 'Not allowed.' });
  }
  console.log("Is it Working ? ")
  console.log("ReqBody : "+req)

var message = {
  notification: {
    title: 'New Message',
    body: 'New Message!'
  },
  token: req.body.token
};
admin.messaging().send(message)
  .then((response) => {
   
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
  
});

send message method

sendMessage(){
    let body = {
      token : "token_string"
    }
    this.http.post(
      'https://us-central1-project.cloudfunctions.net/sendNotifications',
      body
    );
}
Jan Hernandez
  • 4,414
  • 2
  • 12
  • 18
zafer
  • 407
  • 1
  • 4
  • 16
  • Did you tried to hit the function directly using postman or curl? – Jan Hernandez Jan 25 '21 at 15:36
  • @JanHernandez I was able to run the function with "postman".However, I realized that the post method is not working and I researched it a bit more. then I put a subscribe at the end of this.https.post it works now. but the part I cannot understand is that these functions are accessible to everyone, how can I prevent this? – zafer Jan 25 '21 at 15:52
  • 1
    Can you add your code solution as an answer? this it to help others, I found an [answer](https://stackoverflow.com/questions/42751074/how-to-protect-firebase-cloud-function-http-endpoint-to-allow-only-firebase-auth) that can help you, if this information is not enough consider open a new question. – Jan Hernandez Jan 25 '21 at 16:58

1 Answers1

1

When ı add subscribe its work for me ,

sendMessage() (post method)

let body ="abc"
    this.http.post<{s:any}>('https://us-central1-project.cloudfunctions.net/sendNotifications',
      body
    ).subscribe(a=>console.log("This is work"));

After adding subscribe to post method , I added cors for admin.messaging to work.

const cors = require('cors')({ origin: true });

exports.sendNotifications = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
  if (req.method !== 'POST') {
    return res.status(500).json({ message: 'Not allowed.' });
  }
  console.log("Is it Working ? ")
  console.log("ReqBody : "+req.body)
var message = {
  notification: {
    title: 'New Message',
    body: 'New Message!'
  },
  token: "token"
};


admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });
}) 
});
zafer
  • 407
  • 1
  • 4
  • 16