Node.js 中的 GET 请求总是 returns 相同

GET request in Node.js always returns the same

我正在编写一个 Node.js 应用程序,它应该使用 "request" 模块发出 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;

是啊!我让它工作了整个下午,效果很好:

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() 方法实际使用响应。事实证明,你需要在同时抛出许多请求时这样做。