【发布时间】:2015-05-26 08:03:36
【问题描述】:
我正在编写一个 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;
【问题讨论】:
-
您的代码看起来不错。据我了解,这
url返回当前播放的歌曲,并且您的代码每 30 秒发出一次请求。因此,除非当前歌曲播放完毕,否则您将无法取回不同的数据。 -
是的,就是这样。但是歌曲发生了变化,例如,我看到了 cURL 的变化。但不是节点,它似乎缓存了 10 次后的响应。
-
嗯,它对我有用。我让应用程序运行了几分钟,它返回的数据与
curl请求返回的数据相同。 -
是的,它应该工作。但它在 10 次尝试后开始失败。我在某处读过“http”模块有 5 个打开连接限制。也许“请求”模块有这样的限制。我会尝试添加“response.on('data', function() {});”到我的 make request 函数,所以我消耗我的响应,我避免达到这个限制。只是猜测... - stackoverflow.com/questions/16965582/…