Is there a “request” like package using http2?

2019-07-10 08:09发布

问题:

We are using request at work. We now have access to http2 for our server to server requests.

Do you know any node package with the same api (ish) as request that uses http2 ?

回答1:

I faced the same problem and couldn't find a module. This isn't a good solution but you can hack the request module to add http2. As no one has chipped in with a better answer it's worth a mention.

This is what I did:

Add http2 as a boolean to the options object passed into request.

In node_modules/request run:

npm install http2

Open node_modules/request/request.js

Require the http2 module somewhere near the top:

, http2 = require('http2')

Make sure request doesn't add the "host" header (deprecated in HTTP2 and causes an error if the other end is using the http2 node module) so change line 304 (or so) to:

if (!self.hasHeader('host') && !options.http2) {

Add the http2 module to an object declaration on line 468 (or so) so it becomes:

, defaultModules = {'http:':http, 'https:':https, 'http2': http2}

Then make request use the new module after the variable declaration on the previous line. Add this to line 471 (or so):

  if (options.http2) {
    protocol = 'http2';
  }

The rest of the application can remain unchanged, if options.http2 is not set then request behaves like it always does.

In a very unscientific test I found that making this change increased throughput to one service by about 25%.