Ad

How To Send A HTTP/2.0 Request With Node.js

- 1 answer

How can i send a httpVersion 2.0 request in nodejs?

I have tried almost every request module there is, and all of them is httpVersion 1.1

Ad

Answer

Get request:

const http2 = require("http2");
const client = http2.connect("https://www.google.com");

const req = client.request({
 ":path": "/"
});

let data = "";

req.on("response", (headers, flags) => {
 for (const name in headers) {
  console.log(`${name}: ${headers[name]}`);
 }

});

req.on("data", chunk => {
 data += chunk;
});
req.on("end", () => {
 console.log(data);
 client.close();
});
req.end();

POST Request

     let res = "";
      let postbody = JSON.stringify({
       key: value
      });
      let baseurl = 'baseurl'
      let path = '/any-path'
      const client = http2.connect(baseurl);
      const req = client.request({
       ":method": "POST",
       ":path": path,
       "content-type": "application/json",
       "content-length": Buffer.byteLength(postbody),
      });


      req.on("response", (headers, flags) => {
       for (const name in headers) {
        console.log(`${name}: ${headers[name]}`);
       }

      });
      req.on("data", chunk => {
       res = res + chunk;
      });
      req.on("end", () => {
       client.close();
      });

   req.end(postbody)

For more details pls see this official documents: https://nodejs.org/api/http2.html#http2_client_side_example

Ad
source: stackoverflow.com
Ad