将请求发布到Firebase函数时,邮递员说“错误:无法处理请求”

时间:2020-11-10 11:47:48

标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


exports.createNotice = functions.https.onRequest((req, res) => {
  if (req.method !== "POST") {
    return res.status(400).json({ error: "Method not allowed" });
  }

  const newNotice = {
    body: req.body.body,
    userHandle: req.body.userHandle,
    createdAt: admin.firestore().Timestamp.fromData(new Date()),
  };
  admin
    .firestore()
    .collection("notices")
    .add(newNotice)
    .then((doc) => {
      res.json({ message: `document ${doc.id} created successfully` });
    })
    .catch((err) => {
      res.status(500).json({ error: "something went wrong" });
      console.error(err);
    });
});

这是我的职责。当我部署并尝试像这样在Postman上发布请求时:

{
    "body": "New Notice",
    "userHandle": "user"
}

显示错误:无法处理该请求。我希望它更新Firebase上的数据库。创建一个新的通知集合。谁能帮我吗?

1 个答案:

答案 0 :(得分:1)

创建Timestamp时,您的代码有两个错误。

  1. 有一个错字:方法是fromDate()而不是fromData();
  2. 您需要按以下方式调用它:admin.firestore.Timestamp.fromDate(new Date())

另外请注意,对于代码中的第一个块,您应该执行以下操作。无需使用return,请参阅doc

  if (req.method !== "POST") {
    res.status(400).json({ error: "Method not allowed" });
  }