使用Node.js轮询REST服务

occ*_*asl 7 node.js

我正在开发一种服务,每隔一分钟就会对Foursquare进行一些检查,并在NoSQL数据库中保存/更新结果.是使用setInterval包装http.request然后使用数据事件发射器聚合分块响应的最佳方法吗?我计划使用end发射器来解析JSON并在请求完成时推送到NoSQL DB.思考?

occ*_*asl 10

可能有更好的方法,但我最终只使用事件发射器来处理REST响应,如下所示:

var fourSquareGet = {
    host: 'api.foursquare.com',
    port: 443,
    path: '/v2/venues/search?ll=33.88,-119.19&query=burger*',
    method: 'GET'
};
setInterval(function () {
    var reqGet = https.request(fourSquareGet, function (res) {
        var content;

        res.on('data', function (chunk) {
            content += chunk;
        });
        res.on('end', function () {
            // remove 'undefined that appears before JSON for some reason
            content = JSON.parse(content.substring(9, content.length));
            db.checkins.save(content.response.venues, function (err, saved) {
                if (err || !saved) throw err;
            });
            console.info("\nSaved from Foursquare\n");
        });
    });

    reqGet.end();
    reqGet.on('error', function (e) {
        console.error(e);
    });
}, 25000);
Run Code Online (Sandbox Code Playgroud)

但是,我不确定为什么我从foursquare收到的JSON中解析出"undefined".

  • 您必须解析'undefined'的原因是因为您从未初始化`content`.如果,而不是"var content;" 你有"var content ='';" 你不需要剥去任何东西.(当你将'foo'字符串添加到'undefined'时,它会给你字符串"undefinedfoo".) (2认同)

Chr*_*ase 6

我已经修复了@occasl的答案,并为了清晰起见进行了更新:

var https = require('https');

setInterval(function () {

    var rest_options = {
        host: 'api.example.com',
        port: 443,
        path: '/endpoint',
        method: 'GET'
    };

    var request = https.request(rest_options, function(response) {
        var content = "";

        // Handle data chunks
        response.on('data', function(chunk) {
            content += chunk;
        });

        // Once we're done streaming the response, parse it as json.
        response.on('end', function() {
            var data = JSON.parse(content);

            //TODO: Do something with `data`.
        });
    });

    // Report errors
    request.on('error', function(error) {
        console.log("Error while calling endpoint.", error);
    });

    request.end();
}, 5000);
Run Code Online (Sandbox Code Playgroud)

  • 为了将来,只需编辑我的答案,我会接受您的更改没有问题. (6认同)