写了一段用代理请求的代码,可是总会出现socket hang up的问题,我觉得是没有关闭request,但是加了req.end()之后,又会出现下面的错误。 req.abort(); ^ TypeError: Object false has no method ‘abort’ at null._onTimeout (/home/ilolita/node_model/spider/crawler/test/timeOutTest.js:6:9) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
请问大神们这个问题怎么解决??
var http = require(‘http’);
var request_timer = null, req = null; // 请求5秒超时 request_timer = setTimeout(function() { req.abort(); console.log(‘Request Timeout.’); }, 5000);
var options = { host: '180.118.105.153’, port: '18186’, path: ‘http://www.cnodejs.org/’ };
req = http.get(options, function(res) { clearTimeout(request_timer);
// 等待响应60秒超时
var response_timer = setTimeout(function() {
res.destroy();
console.log('Response Timeout.');
}, 60000);
console.log("Got response: " + res.statusCode);
var chunks = [], length = 0;
res.on('data', function(chunk) {
length += chunk.length;
chunks.push(chunk);
});
res.on('end', function() {
clearTimeout(response_timer);
console.log(res.headers);
});
}).on('error’,function(err){ console.log('Error: '+ err ); });
req没定义,所以报“TypeError: Object false has no method 'abort’”。setTimeout可以直接用http.setTimeout,req.setTimeout,res.setTimeout提供的函数。不妨参考一下我写的: https://github.com/xuduo35/simpleproxy/blob/master/testproxy.js