【问题标题】:Why Does My Firebase HTTPS Function Go Silent When I Try to Save to Firestore?当我尝试保存到 Firestore 时,为什么我的 Firebase HTTPS 功能会静默?
【发布时间】:2018-11-06 14:18:58
【问题描述】:

我可以在 Firebase 中编写一个接受 POST 请求的 HTTPS 端点。我可以使用它并从中得到响应。我可以整天 console.log() 。

我记录每一步,因为它决定如何处理请求,但是一旦我尝试保存到 Firestore,整个端点就会静默。步骤 1-7 曾经愉快地使用 console.log(),现在步骤 8 把整个事情吸进了一个黑洞。

我认为我在使用 async/await/promises 时做错了,所以我用一个愚蠢的 setTimeout 承诺替换了“第 8 步”。这很好用:我的承诺会在 2000 毫秒后写入 console.log。然后我认为我保存的数据有问题(因为这一切都是在我尝试修复有关在 Firestore 中存储日期的警告时开始的)。我用 {test: "Test"} 替换了我的数据 - 又是黑洞。

似乎只是保存到数据库的行为会创建一个黑洞。但仅在这一端点上。我有其他人做类似的事情就好了。

我已经研究这个问题好几天了,如果有任何帮助,我们将不胜感激。

app.post("/webhook", async (req: express.Request, res: express.Response) => {
  if(req.body.token !== functions.config().service.verification_token)
    throw new Error("Unauthorized access");

  if(req.body.type === "url_verification")
  {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('CHALLENGE_RESPONSE');
    return;
  }

  res.end("OK");

  if(DEBUG) { console.log("Received a request", req.body); }

  if(req.body.type === "event_callback")
  {
    if(DEBUG) { console.log("This request appears to be an event"); }

    if(req.body.event.type === "message")
    {
      if(DEBUG) { console.log("This event appears to concern a message"); }

      if(shouldIgnoreMessage(req.body.event))
      {
        if(DEBUG) { console.log("Actually, this event is not something we care about. We're done here."); }
        return;
      }

      if(DEBUG) { console.log("Whoa-ho! This is a message from a user! We have to deal with this."); }

      saveToFirebase(req.body).catch(err => console.error(err));
    }
  }
});

【问题讨论】:

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


    【解决方案1】:

    看起来您在承诺之前缺少await

    我还建议删除您的res.end("OK");,因为它会结束响应过程。 或者根据端点中的逻辑是成功还是失败,将其向下移动以给出实际响应。

    试试这个:

    try {    
      const saved = await saveToFirebase(req.body);
      console.log('Saved to firebase', saved)
      return res.sendStatus(200);
    } catch(err) {
      console.log(err);
      return res.sendStatus(500);
    }
    

    【讨论】:

    • 谢谢!我希望在不弄乱 .end() 的情况下做到这一点,因为我的部分要求是快速响应。答案可能最终是发出一条消息,而不是做任何事情。
    • 我会接受这个答案,因为将 res.end() 移到数据库调用的 .then() 中解决了我抱怨的具体问题。我的日志消息再次出现,我得到了一个数据库记录。但我认为最终的答案将是在结束响应后不做任何工作,如stackoverflow.com/questions/43705401/… 所述,并且可能使用 Firebase Cloud Messaging 来触发工作。
    猜你喜欢
    • 1970-01-01
    • 2019-12-03
    • 2018-08-24
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多