如何使用 node.js 发送 HTTP/2.0 请求

Hob*_*823 5 request node.js http2

如何在 nodejs 中发送 httpVersion 2.0 请求?

我已经尝试了几乎所有的请求模块,而且都是 httpVersion 1.1

San*_*tel 5

获取请求

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();
Run Code Online (Sandbox Code Playgroud)

POST 请求

     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)
Run Code Online (Sandbox Code Playgroud)

更多详情请查看官方文档:https : //nodejs.org/api/http2.html#http2_client_side_example