'nodejs http2 client can not gunzip response

we are setting up a nodejs express server, which has to make http requests to another server.

It works fine with axios, but we are now trying to implkement http2 to speed up the requests and reduce some latency.

Now the problem is, if we use the "accept-encoding" : "gzip" header in the request, we are not able to decompress the compressed response.

Following this example, we implemented the request like this:

  const client = http2.connect('https://someserver.com');

  client.on('error', (err) => console.error(err));

  const buffer = Buffer.from(JSON.stringify(body), 'utf-8');


  const req = client.request({
    ':method': 'POST',
    ':scheme': 'https',
    ':path': '/some/api/endpoint',
    'content-type': 'application/json; charset=utf-8',
    'Content-Length': buffer.length,
    'accept-encoding': 'gzip'
  }, { endStream: false });

  req.setEncoding('utf-8');

  let data = '';

  const zip = createGunzip();

  req.pipe(zip);

  req
    .on('response', (headers, flags) => {
      // tslint:disable-next-line: forin
      for (const name in headers) {
        console.log(`HEADER ${name}: ${headers[name]}`);
      }
    })
    .on('data', (chunk) => {
      chunk = chunk.toString("utf-8");
      data += chunk;
    })
    .on('end', () => {
      console.log(`\n END : ${data}`);

      client.close();
    })
    .on('error', (error) => {
      console.log('ERROR : ', error);
    });

  console.log('SENDING ' + JSON.stringify(body));
  req.write(JSON.stringify(body));

  req.end();

But we keep receiving an incorrect header check. The "HEADER" console.log shows that "content-encoding" : "gzip" and the "END" console.log show some garbage characters, which to me looks like compressed data.

We tried Gunzip, unzip and inflate, but to no avail.

Any suggestion on what is wrong here?

Thanks you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source