gpt4 book ai didi

node.js - AWS Lambda NodeJS HTTP请求,从API打印数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:35 25 4
gpt4 key购买 nike

下面的代码在 Lambda 中返回“得到响应:301”。我已经在 php、python 和 Node.js 中尝试过这段代码。将此链接粘贴到浏览器中将返回 JSON 数据,如下图所示。如何获得打印相同数据的代码?我最终需要将数据放入 Mongo 中。我可以让 php 和 python 在本地打印数据,但不能在 Lambda 中打印。

我认为这与the callback() shown here有关,我正在尝试实现它。

enter image description here

var http = require('http');
var url = 'http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo';
exports.handler = function (event, context) {
http.get(url, function(res) {
console.log("Got response: " + res.statusCode);

res.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
};

我将代码更新为:

var http = require('http');
var url = 'http://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo';
exports.handler = function (event, context) {
http.get(url, function(res) {
var data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { console.log("BODY: " + data); });
}).on('error', (e) => { console.log("Got error: " + e.message);});
};

得到了这样的回复:

START RequestId: 19a21615-7d09-11e7-93cc-cb3212ad23c5 Version: $LATEST 2017-08-09T13:46:10.102Z 19a21615-7d09-11e7-93cc-cb3212ad23c5    BODY:  END RequestId: 19a21615-7d09-11e7-93cc-cb3212ad23c5 REPORT RequestId: 19a21615-7d09-11e7-93cc-cb3212ad23c5   Duration: 277.04 ms Billed Duration: 300 ms     Memory Size: 128 MB Max Memory Used: 19 MB

最佳答案

以 block 的形式接收的数据,以便打印监听“结束”事件然后记录它所需的所有数据。尝试在每个数据事件上附加 block ,并在收到结束事件时记录所有数据。

var https = require('https');
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo';
exports.handler = function (event, context) {
https.get(url, function(res) {
var data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { console.log("BODY: " + data); });
}).on('error', (e) => { console.log("Got error: " + e.message);});
};

关于node.js - AWS Lambda NodeJS HTTP请求,从API打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45581905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com