2017-08-09 251 views
0

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

我认为它与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 
+0

您可能需要发送一个有效的User-Agent头,浏览器会自动为您做,但Node不会。您正在使用的PHP和Python库可能正在发送一个。也有Node的库也会。 –

回答

3

要想在块接收的数据打印所有数据你需要听'结束'事件,然后记录它。尝试在每个数据事件上附加块,以及接收到的结束事件记录所有数据。

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);}); 
}; 
+0

谢谢,但它仍然不显示数据。我认为这与在Lambda函数内部有关。我编辑了我的问题以包含您的代码和输出。 –

+1

将http更改为https为我工作。请在回答中找到我的编辑 –

+0

你是我的英雄。我已经为此工作了好几个星期,终于有效了。谢谢。 –

相关问题