首页 > 解决方案 > 如何在 Firebase Functions 中编写 Javascript GET 请求?

问题描述

我正在尝试编写一个简单的 GET 请求,该请求返回 JSON 数据https://hacker-news.firebaseio.com/v0/item/160705.json

我已经尝试了很多东西,但似乎没有任何效果。(我在付费的 Firebase 计划中,允许向外部 API 发出请求)。我编写函数,然后运行firebase deploy并执行该函数,但它要么超时,要么引发另一个错误。

作为测试,这个简单的 HTTP 调用可以正常工作:

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send('test');
})

但是,当我尝试运行以下命令并点击 HN API 时,它会超时:

exports.helloWorld = functions.https.onRequest((request, response) => {
  request.get('https://hacker-news.firebaseio.com/v0/item/160705.json', function (error, res, body) {
    if (!error && res.statusCode == 200) {
      console.log(body) // Print the google web page.
    }
    return response.send("") // this terminates the function
  })
})

编辑

上述函数的 firebase 日志显示: Function execution started Function execution took 60002 ms, finished with status: 'timeout'

我还尝试了其他几件事,例如:

const options = {
  host: 'hacker-news.firebaseio.com',
  path: '/v0/item/160705.json'
};

// make the request
exports.hackerNews = functions.https.onRequest(options, (resp) => {
  console.log(resp)
});

但这失败了 500Error: could not handle the requestReferrer Policy: no-referrer-when-downgrade

在 firebase 函数中编写一个简单的 GET 请求应该不难,所以我一定是在做一些愚蠢的事情。谢谢。

标签: javascriptfirebaseecmascript-6google-cloud-functions

解决方案


我想到了:

exports.helloWorld = functions.https.onRequest((req, res) => {
  request.get('https://hacker-news.firebaseio.com/v0/item/160705', (error, response, body) => {
    if (!error && response.statusCode === 200) {
      return res.send(body);
    }
    return res.send('ERROR: ' + error.message);
  })
});

显然你必须在成功或错误时返回一些东西,你只是不能执行另一个函数,比如 console.log()。


推荐阅读