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

我正在尝试在使用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事件:

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

});

以上是 如何在Node中的http.request()上设置超时? 的全部内容, 来源链接: utcz.com/qa/426635.html

回到顶部