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

问题描述:

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

I'm writing a node.js application that needs to talk to a server. It establishes an http connection with the following code:

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

我在node.js文档中没有看到用于设置连接超时的任何选项,默认情况下它似乎设置为20秒.我遇到的问题是,我在中国的用户似乎使用的是缓慢或不稳定的网络,有时他们会超时,无法连接到我们在美国的数据中心.我想将超时时间增加到1分钟,以查看是否可以解决该问题.

I don't see any option in the node.js documentation for setting a timeout on the connection, and it seems to be set to 20 seconds by default. The problem I'm having is that I have users in China on what appears to be a slow or flaky network, who sometimes hit the timeout connecting to our datacenter in the US. I'd like to increase the timeout to 1 minute, to see if that fixes it for them.

在node.js中有办法做到这一点吗?

Is there a way to do that in node.js?

尝试

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

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