下面的代碼在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的庫也會。 –