2014-05-25 52 views
4

因此,我一直在使用sailsjs從外部網站請求json數據,然後將該數據發佈到創建路徑。當我第一次運行它時,它會工作大約10-12次,然後應用程序將會崩潰,並且event.js會拋出;連接ETIMEDOUT什麼是從Node.js中檢索JSON的最佳方式

尋找更好的方法來請求https://cex.io/api/ticker/GHS/BTC的json數據。

所以我使用sailsjs並在config/bootstrap.js文件中添加了我的服務來運行。

module.exports.bootstrap = function (cb) { 

    // My 
    tickerService.ticker(); 

    // Runs the app 
    cb(); 
}; 

這是我的嘗試之一〜文件API /服務/ tickerservice.js

function storeTicker(){ 
    console.log('Running!'); 

    //retrieves info from https://cex.io/api/ticker/GHS/BTC 
    require("cexapi").ticker('GHS/BTC', function(param){ 

     console.log(param); 

     Tickerchart.create(param, function tickerchartCreated (err, tickerchart) {}); 

    }); 
} 

module.exports.ticker = function(){ 

    setInterval(storeTicker, 6000); 

}; 

Cex.io圖書館Github上 https://github.com/matveyco/cex.io-api-node.js/blob/master/cexapi.js

+0

你嘗試使用節點的HTTP API發出請求並得到JSON字符串數據可能? –

+0

是的,到目前爲止,它似乎是錯誤處理。當一個請求無法檢索JSON時,它會引發錯誤並崩潰應用程序。所以我正在研究如何在不使應用程序崩潰的情況下捕獲錯誤。 – jemiloii

回答

1

我使用的模塊請求,看着它的錯誤。我也升級到帆v0.10.x應用程序不會再崩潰:d

function storeTickerchart(){ 
    //console.log('Running!'); 
    var request = require("request"); 

    var url = "https://cex.io/api/ticker/GHS/BTC"; 

    request({ 
     url: url, 
     json: true 
    }, function (error, response, body) { 

     if (!error && response.statusCode === 200) { 
      //console.log(body); //Print the json response 
      Tickerchart.create(body, function tickerchartCreated (error, tickerchart) { 
       if(error) console.log("Oops Error"); 
      }); 
     } 
    }); 



} 

module.exports.ticker = function(){ 

    setInterval(storeTickerchart, 5000); 

}; 
相關問題