我正在尝试在使用http.request且没有运气的HTTP客户端上设置超时。到目前为止,我所做的是:
var options = { ... } var req = http.request(options, function(res) { // Usual stuff: on(data), on(end), chunks, etc... } /* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */ req.socket.setTimeout(myTimeout); req.socket.on('timeout', function() { req.abort(); }); req.write('something'); req.end();
有什么提示吗?
现在可以使用timeoutoption和相应的request事件:
timeout
// set the desired timeout in options const options = { //... timeout: 3000, }; // create a request const request = http.request(options, response => { // your callback here }); // use its "timeout" event to abort the request request.on('timeout', () => { request.abort(); });