如何在node.js中为客户端http连接设置超时

Dan*_*ist 10 node.js

我正在编写一个需要与服务器通信的node.js应用程序.它使用以下代码建立http连接:

var client = http.createClient(u.port, u.hostname, u.secure);
client.on("error", function(exception) {
    logger.error("error from client");
});
var request = client.request(method, u.path, headers);
Run Code Online (Sandbox Code Playgroud)

我没有在node.js文档中看到任何用于在连接上设置超时的选项,默认情况下它似乎设置为20秒.我遇到的问题是我在中国的用户似乎是一个缓慢或片状的网络,他们有时会遇到连接到美国数据中心的超时.我想将超时时间增加到1分钟,看看是否能为它们修复它.

有没有办法在node.js中这样做?

Mat*_*pus 8

尝试

request.socket.setTimeout(60000); // 60秒


Tob*_*ede 4

我认为你可以这样做:

request.connection.setTimeout(60000)
Run Code Online (Sandbox Code Playgroud)

request.connection 返回与连接关联的 net.Stream 对象。net.Stream 有一个 setTimeout 方法。