javascript - 如何在 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 request
和Referrer Policy: no-referrer-when-downgrade
在 firebase 函数中编写一个简单的 GET 请求应该不难,所以我一定是在做一些愚蠢的事情。谢谢。
解决方案
我想到了:
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()。
推荐阅读
- javascript - 如何让元素重新出现?
- python - 特殊列表视图
- jestjs - 如何修复来自赛普拉斯测试的开玩笑/无独立预期?
- google-cloud-platform - 无效的参数被传递给 CloudDataFusionPipelineStateSensor 'failure_statuses'
- python - 在 NoElementException 之后继续循环
- amazon-web-services - 海王星 Jupyter 笔记本未显示图形选项卡
- python - 存储在 numpy.array() 中的类对象无法正常工作
- python - 你如何概括 tkinter 中的文件路径?
- module - mod_restful 设置使用的语法
- amazon-web-services - 使用 KMS 加密创建 AmazonS3Client