【问题标题】:How to make multiple fetch requests inside Firebase functions?如何在 Firebase 函数中发出多个获取请求?
【发布时间】:2020-11-16 20:39:17
【问题描述】:

我正在尝试在定期运行的函数中发出 2 个获取请求。

exports.scheduledPay = functions.pubsub.schedule('1 of month 07:00').timeZone('America/New_York').onRun((context) => {
  //1. fetch for getting token ...
  //2. fetch for making Paypal batch request using that token
    fetch("https://api.sandbox.paypal.com/v1/payments/payouts", {
      method: 'POST',
      headers: {"Authorization":"Basic QWJ4aUhTaWM5cmp2NUpQdEV2WUhaMi1hWmVySWFoTHdDVDEza004UURLY3RMWGtXN3lpTFRfVGpFVllVMXB5NFhKcGtxXzdYSVpYRmhkaFc6RVBUbUVZSWg2OE1FVG9FSjEyT0lHdzFKWkFGNTVza2Q2SjNiRmpLYkxMTEJiOTY3akRhQkdRREt1S29yTWN4amZ3Rm00X0VCa1dvUzJkejn="},
      body: {"grant_type":"client_credentials"},
      redirect: 'follow'
    })
    .then(response => {return response.text()})
    .then(result => {console.log(result);
      return null;
    })
    .catch(error => console.log('error', error));
}

但是,我不断收到此错误。

ReferenceError: fetch is not defined
    at exports.scheduledAward.functions.pubsub.schedule.timeZone.onRun (/workspace/index.js:230:5)
    at cloudFunction (/workspace/node_modules/firebase-functions/lib/cloud-functions.js:130:23)
    at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:199:28)
    at process._tickCallback (internal/process/next_tick.js:68:7) 

【问题讨论】:

  • 嗨 Dinaol,欢迎来到 SO!您的问题似乎有一个潜台词“这是我的问题,为我解决”,不幸的是,这不是 SO 的用途。对于初学者来说,问题的主体甚至没有问题,只有陈述。您是否尝试过研究收到的错误消息?从字面上看,Google 上的第一个搜索结果会为您提供所需的内容。

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


【解决方案1】:

Cloud Functions 在 nodejs JavaScript 环境中运行。这与浏览器 JavaScript 环境非常不同。您将无法访问浏览器提供的 fetch() 函数 - 这解释了错误消息。

您需要做的是使用为 nodejs 构建的其他类型的 HTTP 客户端库。有很多流行的选项,我建议您通过web search 找到一个。

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2021-05-02
    • 2019-08-10
    相关资源
    最近更新 更多