在Node.js中从URL检索JSON的最佳方法是什么?

4
我一直在使用sailsjs从外部网站请求json数据,然后将该数据发布到创建路由。当我第一次运行它时,它会工作约10-12次,然后应用程序将崩溃,并显示event.js throw er; connect ETIMEDOUT。
寻找更好的方法从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/services/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


你尝试过使用Node的HTTP API来发起请求并获取JSON字符串数据吗? - Chetan Bhasin
是的,我已经开始研究了。目前看来问题似乎出在错误处理上。当一个请求无法检索到JSON时,它会抛出一个错误并导致应用程序崩溃。因此,我正在研究如何在不崩溃应用程序的情况下捕获错误。 - jemiloii
1个回答

1

我使用了请求模块并监视了它的错误。我还将应用程序升级到 sails 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);

};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接