为了账号安全,请及时绑定邮箱和手机立即绑定

发送请求后 Firebase http 无法设置标头

发送请求后 Firebase http 无法设置标头

Qyouu 2023-04-20 10:05:39
我正在创建一个与 API 联系的 HTTP 可调用函数。但是,发回 200 时出现错误。我认为这与我在使用异步函数时犯的错误有关。这是我的代码。exports.organisationDataToTemp = functions.region('europe-west3').https.onRequest((req, res) => {  res.set('Access-Control-Allow-Origin', '*');  const GETparam = req.query.kvk;  const KvK = GETparam.toString();  //Test if KvK number is already in temp collection  const snapshot = db.collection('temp').where('information.kvkNumber', '==', KvK).get()    .then(function(querySnapshot) {      querySnapshot.forEach(function(doc) {        //This is where it needs to send the header and it fails. I do get here only when I need this code to run, but it still fails        console.log('kvk number already in temp collection');        res.status(200).send(doc.id);        return;      });    });  //Irrelevant code  //Make API call using the provided KvK number  const keyName = 'VitozFMIS';  const API_key = 'sdfghjqwertyuiopdfghytrdcvbjftyujnbvc';  //Call the first JSON  const _EXTERNAL_URL = 'https://api.kvk.nl/api/v2/testprofile/companies?kvkNumber=' + KvK + '&' + keyName + '=' + API_key + '&startPage=1';  fetch(_EXTERNAL_URL)      .then(response => response.json())      .then(data => {        const total = data.data.totalItems;        for(n=1;n<=total;n++){          const API = 'https://api.kvk.nl/api/v2/testprofile/companies?kvkNumber=' + KvK + '&' + keyName + '=' + API_key + '&startPage=' + n;          //irrelevant code                  //Make the API call          fetch(API)            .then(resp => resp.json())            .then(data => {                //irrelevant code            });        }  });  //Return 200 if no errors occured  res.status(200).send(cleanupID);  return;});通常,代码完全按需要运行,但是当 kvk 号已经在集合中时,它需要将文档 ID 发送回 200。我不确定,但我认为这是因为它在这个代码之前发送了另一个代码,但我不明白为什么会失败。有人知道什么失败了吗?
查看完整描述

1 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

在发生任何其他事情之前,这行代码总是会立即返回 200 响应:

res.status(200).send(cleanupID);

那是因为您使用的 Firestore 和 fetch API 是异步的并且会立即返回。您提供的回调会在结果可用后的一段时间后执行。调用then不会阻止您的代码继续 - 它只是建立一个回调,以便在 promise 解决时运行。

Cloud Functions 要求发送响应必须是您的函数所做的最后一件事,因此您应该等到所有工作完全成功或失败后再发送响应。

您将需要构建您的代码以使用承诺中的回调来决定要做什么。所有的逻辑大部分都在回调中,或者通过返回另一个承诺推迟到另一个回调。


查看完整回答
反对 回复 2023-04-20
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信