如何在Firebase函数中编写Javascript GET请求?
我试图编写一个简单的GET请求,返回如何在Firebase函数中编写Javascript GET请求?,javascript,firebase,ecmascript-6,google-cloud-functions,Javascript,Firebase,Ecmascript 6,Google Cloud Functions,我试图编写一个简单的GET请求,返回JSON数据https://hacker-news.firebaseio.com/v0/item/160705.json 我试过很多方法,但似乎都不管用。(我在付费Firebase计划中,该计划允许请求外部API)。我编写函数,然后运行firebase deploy并执行该函数,但它要么超时,要么抛出另一个错误 作为测试,这个简单的HTTP调用工作正常: exports.helloWorld = functions.https.onRequest((reque
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日志显示:
功能执行已开始
函数执行耗时60002毫秒,状态为“超时”
我还尝试了其他一些方法,例如:
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)
});
但这失败了,错误为500:无法处理请求
和推荐人策略:降级时没有推荐人
在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()。Firebase控制台中的日志说明了什么?顺便说一句,您的第二个示例是导出。hackerNews根本不起作用。HTTP类型函数只接受两个参数,一个express.js请求和一个响应。@DougStevenson我编辑了我的问题,日志上说它超时了。