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

标签 node.js request http2

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

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

最佳答案

获取请求:

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 请求

     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)

更多细节请看官方文档: https://nodejs.org/api/http2.html#http2_client_side_example

关于node.js - 如何使用 node.js 发送 HTTP/2.0 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58156747/

相关文章:

c++ - node.js 附加组件中未捕获异常

php - 请求的来源

ios - obj-c AFNetworking 2.0 POST 请求不起作用

webpack - 在 HTTP2 环境中从 Webpack2 包中提取 CSS 是否值得?

javascript - node.js 支持什么版本的 Javascript

node.js - 在 Node + Mongo 中强制执行单个 DB Writer

javascript - crypto.getRandomValues(new Uint32Array(1))[0]/lim 可以为负数吗?

asp.net - 保护我自己免受跨站点脚本的影响

http - 谷歌使用 HTTP/2.0?

http - 在golang中测试http.Pusher和推送功能