在 http 请求上设置基于套接字的超时
Setting socket based timeout on http request
如果持续时间超过 10 秒,下面的代码会中止请求。
是否可以使用 http
模块根据请求设置基于 socket
的超时?
此外,我应该使用套接字并请求超时吗?
var abortRequestError;
var timeout = 10000;
var requestObject = {
host: 'xx.xx.xx.xx',
path: '/api',
port: 10000,
method: 'GET'
};
var req = http.request(requestObject, function(res) {
var responseBody = '';
res.on('data', function(data) {
responseBody += data;
});
res.on('end', function() {
console.log(abortRequestError);
});
}).on('error', function(error) {
error = abortRequestError ? abortRequestError : error;
console.log(error);
}).setTimeout(timeout, function() {
abortRequestError = new Error('Request timed out');
req.abort();
});
对于 连接超时 ,节点使用 OS 默认值。简而言之,当你在一段时间内根本无法连接到服务器时,就会触发这些。
建立连接后,request#setTimeout()
function sets up idle timeout, which triggers when there have been no network activity for a period of time. Sounds like this is what you want. (Note that underneath it simply calls socket#setTimeout
创建套接字时,因此无需调用两者。)
对于其他类型的逻辑,您需要通过手动使用 timers 来设置自己的东西。但是您提供的代码应该可以很好地满足您的需求——如果在连接到服务器后,服务器停止发送数据的时间超过 10,000 毫秒,则会触发超时。
如果持续时间超过 10 秒,下面的代码会中止请求。
是否可以使用 http
模块根据请求设置基于 socket
的超时?
此外,我应该使用套接字并请求超时吗?
var abortRequestError;
var timeout = 10000;
var requestObject = {
host: 'xx.xx.xx.xx',
path: '/api',
port: 10000,
method: 'GET'
};
var req = http.request(requestObject, function(res) {
var responseBody = '';
res.on('data', function(data) {
responseBody += data;
});
res.on('end', function() {
console.log(abortRequestError);
});
}).on('error', function(error) {
error = abortRequestError ? abortRequestError : error;
console.log(error);
}).setTimeout(timeout, function() {
abortRequestError = new Error('Request timed out');
req.abort();
});
对于 连接超时 ,节点使用 OS 默认值。简而言之,当你在一段时间内根本无法连接到服务器时,就会触发这些。
建立连接后,request#setTimeout()
function sets up idle timeout, which triggers when there have been no network activity for a period of time. Sounds like this is what you want. (Note that underneath it simply calls socket#setTimeout
创建套接字时,因此无需调用两者。)
对于其他类型的逻辑,您需要通过手动使用 timers 来设置自己的东西。但是您提供的代码应该可以很好地满足您的需求——如果在连接到服务器后,服务器停止发送数据的时间超过 10,000 毫秒,则会触发超时。