5

我正在运行一个 node.js 服务器 A,它使用 superagent 向另一台服务器 B 发出 HTTP 请求。

我调查了服务器 B 上的请求,看到标头和 httpVersionconnection是:close1.1

var http = require('http');
var request = require('superagent');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('req.httpVersion seen on server:' + req.httpVersion);
  res.write('\nreq.headers.connection seen on server:' + req.headers.connection);
  res.end();
}).listen(1337, '0.0.0.0');

request
  .get('localhost:1337/helloword')
  .end(function (err, res) {
    console.log(res.text);
  });

这将导致:

req.httpVersion seen on server:1.1
req.headers.connection seen on server:close

但是,如果我从浏览器访问同一服务器,我会得到:

req.httpVersion seen on server:1.1
req.headers.connection seen on server:keep-alive

https://www.rfc-editor.org/rfc/rfc2616#page-172我了解到这keep-alive是 HTTP 1.1 的默认设置,除非使用Connection: close.

所以,我的问题是:

  • 为什么 Superagent / Node.js 明确将请求设置为不使用 keep-alive / 持久连接?
  • 如何强制 Superagent / Node.js 使用保持活动连接?
  • 如何进一步影响确切的行为(保持打开的连接数、超时等)?
4

3 回答 3

12

它似乎没有记录,但您可以使用函数将 http 代理传递给 superagent agent。因此,您可以使用此模块创建一个保持活动状态的代理:https : //www.npmjs.org/package/agentkeepalive 并将其传递给超级代理。

像这样的东西:

util = require('util');
util.debuglog = require('debuglog');
var http = require('http');
var request = require('superagent');
var Agent = require('agentkeepalive');

var keepaliveAgent = new Agent({
  maxSockets: 100,
  maxFreeSockets: 10,
  timeout: 60000,
  keepAliveTimeout: 30000 // free socket keepalive for 30 seconds
});

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('req.httpVersion seen on server:' + req.httpVersion);
  res.write('\nreq.headers.connection seen on server:' + req.headers.connection);
  res.end();
}).listen(1337, '0.0.0.0');

request
  .get('localhost:1337/helloword')
  .agent(keepaliveAgent)
  .end(function (err, res) {
    console.log(res.text);
  });
于 2014-10-12T10:51:26.447 回答
1

浏览器可以重用套接字句柄,因此它将标头发Connection: keep-alive送到服务器。

如果您想保持连接,您可以像这样发送该标头:

request
.get('localhost:1337/helloword')
.set('Connection', 'keep-alive')
.end(function (err, res) {
   console.log(res.text);
});
于 2013-12-23T14:12:11.987 回答
0

对于 superagent .timeout(5000) 也可以使用。

                    await superagent.get(`${anyurl}`, { rejectUnauthorized: false })
                        .set({ "Accept": "application/json", "Content-Type": "application/json", })
                        .auth(username, password, { "type": "auto" })
                        .timeout(1000)
于 2020-05-19T05:25:07.553 回答