【问题标题】:Firebase cloud Function How should the post method be?Firebase cloud Function post方法应该如何?
【发布时间】:2021-04-27 23:14:55
【问题描述】:

我无法运行该功能,为什么?我的目标是向这个函数发送令牌,但我无法进入这个函数。

firebase 函数控制台没有输出 (console.log("Is it Working ? ") console.log("ReqBody : "+req)

我哪里做错了?

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

发送消息方法

sendMessage(){
    let body = {
      token : "token_string"
    }
    this.http.post(
      'https://us-central1-project.cloudfunctions.net/sendNotifications',
      body
    );
}

【问题讨论】:

  • 你试过直接用 postman 或者 curl 打函数吗?
  • @JanHernandez 我能够使用“postman”运行该功能。但是,我意识到 post 方法不起作用,我对其进行了更多研究。然后我在 this.https.post 的末尾添加了一个订阅,它现在可以工作了。但我不能理解的是这些功能对每个人都可以访问,我该如何防止呢?
  • 您可以添加您的代码解决方案作为答案吗?这是为了帮助别人,我找到了一个可以帮助你的answer,如果这些信息还不够,请考虑打开一个新问题。

标签: angularjs firebase ionic-framework google-cloud-functions


【解决方案1】:

当我为我添加订阅它的工作时,

sendMessage()(发布方法)

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

添加 subscribe to post 方法后,我添加了 cors 以便 admin.messaging 工作。

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

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 2018-09-13
    • 2020-10-26
    • 2018-10-01
    • 2018-01-24
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多