2014-05-25 53 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); 

}; 
相关问题