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

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

问题描述

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

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

任何提示?

推荐答案

使用你的代码,问题是在尝试在套接字对象上设置东西之前你还没有等待套接字分配给请求。所有这些都是异步的:

Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so:

var options = { ... }
var req = http.request(options, function(res) {
  // Usual stuff: on(data), on(end), chunks, etc...
});

req.on('socket', function (socket) {
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        req.abort();
    });
});

req.on('error', function(err) {
    if (err.code === "ECONNRESET") {
        console.log("Timeout occurs");
        //specific error treatment
    }
    //other error treatment
});

req.write('something');
req.end();

在为请求分配套接字对象时会触发'socket'事件。

The 'socket' event is fired when the request is assigned a socket object.

这篇关于如何在Node中的http.request()上设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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