Florian Barth
Florian Barth

Reputation: 1392

Node.js - Request: Specifying custom agent that can handle http & https

I'm using request.defaults(..) to - amongst other things - set a custom http agent for my requests (setting up maxSockets and keepAlive).

const agent = new http.Agent({
        keepAlive: true,
        maxSockets: 42
      })
const requestWithCustomAgent = request.defaults({
        agent,
        json: true,
        headers: {
          'User-Agent': 'amazing agent'
        }        
      })

When accessing a URL with scheme https this errors with Error: Protocol "https:" not supported. Expected "http:". Vice-versa for https.Agent and scheme http.

Is there any way to "tell" request to handle http request with one agent and https with another?

One could invest some unicorn blood and do dark magic like:

if(url.startsWith('https') {/* use on agent */} else { /* use the other */}

But that feels hack'ish.

Is something like:

const requestWithCustomAgent = request.defaults({
    agents: {
       'http': httpAgent,
       'https': httpsAgent
    },
    json: true,
    headers: {
      'User-Agent': 'amazing agent'
    }        
  })

possible?

Help appreciated ;)

Upvotes: 2

Views: 2566

Answers (1)

robertklep
robertklep

Reputation: 203304

If you use agentOptions instead of passing an http(s).Agent instance, request will create an agent for you for each scheme that is used:

const requestWithCustomAgent = request.defaults({
  agentOptions : {
    keepAlive  : true,
    maxSockets : 42
  },
  json    : true,
  headers : {
    'User-Agent': 'amazing agent'
  }        
})

Upvotes: 4

Related Questions