如何在 Node 中的 http.request() 上设置超时? [英] How to set a timeout on a http.request() in Node?

查看:86
本文介绍了如何在 Node 中的 http.request() 上设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用 http.request 的 HTTP 客户端上设置超时,但没有运气.到目前为止,我所做的是:

var options = { ... }var req = http.request(options, function(res) {//常见的东西:on(data), on(end), chunks, 等等...}/* 这不起作用太多......有时套接字未准备好(未定义)特别是在快速请求序列上 */req.socket.setTimeout(myTimeout);req.socket.on('超时', function() {req.abort();});req.write('东西');请求结束();

有什么提示吗?

解决方案

只是为了澄清上面的答案::>

现在可以使用timeout选项和相应的请求事件:

//在选项中设置所需的超时时间常量选项 = {//...超时:3000,};//创建请求const request = http.request(options, response => {//你的回调在这里});//使用它的超时"事件来中止请求request.on('超时', () => {request.abort();});

I'm trying to set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this:

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

Any hints?

解决方案

Just to clarify the answer above:

Now it is possible to use timeout option and the corresponding request event:

// 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() 上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆