【发布时间】:2017-03-24 10:35:56
【问题描述】:
如果持续时间超过 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();
});
【问题讨论】:
-
你的意思是连接超时吗?
-
只有数据流中断10秒才能认为是坏了..是连接超时吗?
-
您的代码为您想要实现的目标调用了正确的函数——套接字空闲时超时;也许问题出在其他地方。你想达到什么目标,什么是行不通的?
标签: node.js sockets http timeout