Node.js中的GET请求始终返回相同的内容

时间:2015-03-23 10:53:37

标签: node.js express request

我正在编写一个Node.js应用程序,该应用程序应使用“请求”模块发出HTTP请求,并使用一些参数保存Parse中的响应等等。我使用setInterval()作为循环。

问题是我总是得到相同的响应,比如缓存或其他东西。如果我在本地机器上执行cURL,我会看到实际的数据,但是Node.js中的循环似乎总是得到相同的响应。

编辑代码:

//Loop
setInterval(function(){
    try {
        foo.make_request();
    }catch(e){
        console.log(e);
    }
}, 30 * 1000); //30 secs

和我的make_request函数:

function _make_request(){
    //Configure the request
    var options = {
        url: 'http://player.rockfm.fm/rdsrock.php',
        method: 'GET'
    };

    //Start the request
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Print out the response body
            var artist = body.substring(0, body.indexOf(':'));
            var title  = body.substring(body.indexOf(':')+3, body.indexOf('@')-1);
            console.log(artist + " - " + title);
            //upload to Parse etc etc
        }    
    });
}

module.exports.make_request = _make_request;

1 个答案:

答案 0 :(得分:0)

呀!我整个下午都让它工作,而且效果很好:

request(options, function (error, response, body) {
    response.on('data', function() {});
    if (!error && response.statusCode == 200) {
        // Print out the response body
        var artist = body.substring(0, body.indexOf(':'));
        var title  = body.substring(body.indexOf(':')+3, body.indexOf('@')-1);
        console.log(artist + " - " + title);
        //upload to Parse etc etc
    }    
});

解决方案是使用.on()方法实际使用响应。事实证明,你需要在同时抛出许多请求时这样做。

相关问题