在nodejs中挂起一段时间后的http连接

Hang up the http connection after some duration in nodejs

本文关键字:http 连接 一段时间 nodejs 挂起      更新时间:2023-09-26

我需要写一个程序从nodejs中的一些现有服务中获得一些json数据。但是,通过注意我的应用程序中的实时条件,我需要确保答案准备时间不会超过2秒。在那段时间之后,我想切断已经建立的连接,并从我自己的数据库中给客户端我的数据。我已经搜索了很多,但我发现的唯一的事情是设置超时的套接字在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();
});

以上代码只会在服务器不可达或无法联系时执行。但我的问题是强迫连接关闭。有人知道吗?

尝试一下请求模块。它非常适合这样的内容:

var request = require('request');
request({
  method: 'GET',
  uri: 'http://www.example.com',
  timeout: 2000,
}, (err, response, body) => {
  if (err) {
    return console.error(err);
  }
  console.log(response);
});