一尘不染

如何在Node中的http.request()上设置超时?

node.js

我正在尝试在使用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();

有什么提示吗?


阅读 880

收藏
2020-07-07

共1个答案

一尘不染

现在可以使用timeoutoption和相应的request事件:

// 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();
});
2020-07-07