下面的代码在Lambda中返回“有回应:301”。我已经在php,python和Node中试过这段代码。将此链接粘贴到浏览器中将返回JSON数据,如图所示。如何获得打印出相同数据的代码?我需要最终将数据放入Mongo中。我可以让php和python在本地打印数据,但不能在Lambda中打印。AWS Lambda NodeJS HTTP请求,从API打印数据
我认为它与the callback() shown 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
您可能需要发送一个有效的User-Agent头,浏览器会自动为您做,但Node不会。您正在使用的PHP和Python库可能正在发送一个。也有Node的库也会。 –