我试图在使用HTTP的HTTP客户端上设置超时.没有运气的请求.到目前为止,我所做的是:

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

有什么提示吗?

推荐答案

为了澄清这answer above个问题:

现在可以使用timeout选项和相应的请求事件:

// set the desired timeout in options
const options = {
    //...
    timeout: 3000,
};

// create a request
const request = http.request(options, response => {
    // your callback here
});

// use its "timeout" event to abort the request
request.on('timeout', () => {
    request.destroy();
});

Node.js相关问答推荐

Express 4.18正文解析

从mongodb集合中获取每分钟数据的每小时数据

合并Shift对象数组以创建最终的排班表

在构建完成后,将AddedFiles文件夹的内容复制到dist文件夹

如何使用mongoose引用不在项目中的模型

MongoDB - 查找查询以判断是否存在少量字段,结合字段上的 AND

未捕获的错误: 只能用作 元素的子元素,永远不会直接呈现.请将您的 包裹在

如何通过node下载zip并直接解压zip?

我应该转译我的 TypeScript 应用程序吗?

MERN 堆栈项目中的 React [create-react-app] 正在提供依赖项

Node.js 大文件上传到 MongoDB 阻塞了事件循环和工作池

等到文件上传完成的有效方法(mongoose )

为当前目录提供服务的简单文件服务器

Node.js 中空函数的简写

按日期时间字段获取最新的 MongoDB 记录

nodejs v10.3.0 的 gulp 任务问题:src\node_contextify.cc:629: Assertion `args[1]->IsString()' failed

什么是 JavaScript 中的REPL?

使用 Node.js 我得到错误:EISDIR,读取

node --experimental-modules,请求的模块不提供名为的导出

Nodejs将字符串转换为UTF-8