2017-08-09 253 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

你是我的英雄。我已經爲此工作了好幾個星期,終於有效了。謝謝。 –

相關問題