keep-alive connection with Superagent

Viewed 8896

I'm running a node.js server A which uses superagent to issue HTTP requests to another server B.

I investigated the request on server B and saw the the header connection being close and the httpVersion being 1.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);
  });

This leads to:

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

However if I access the same server from a browser I get:

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

From https://www.rfc-editor.org/rfc/rfc2616#page-172 I learned that keep-alive is the default for HTTP 1.1 unless declared otherwise by using Connection: close.

So, my questions are:

  • Why does Superagent / Node.js explicitly set the request to not use keep-alive / persistent connections?
  • How can I force Superagent / Node.js to use keep-alive connections?
  • How can I further influence the exact behaviour (how many connections to keep open, timeouts etc.)?
3 Answers

For superagent .timeout(5000) is also available to use.

                    await superagent.get(`${anyurl}`, { rejectUnauthorized: false })
                        .set({ "Accept": "application/json", "Content-Type": "application/json", })
                        .auth(username, password, { "type": "auto" })
                        .timeout(1000)
Related