【问题标题】:Performing outgoing HTTP2 requests in NodeJS在 NodeJS 中执行传出 HTTP2 请求
【发布时间】:2018-09-03 03:08:49
【问题描述】:

我检查了NodeJS documentation,但找不到任何有关如何使以下代码使用 HTTP2 执行请求的信息:

const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.end()

即使是最新版本的 NodeJS 也不支持这一点?

【问题讨论】:

    标签: node.js http2


    【解决方案1】:

    这在v9.9.0 中可用。你可以看看HTTP2 in Nodejs。如果你想要整个东西,你可以在 HTTP2 中创建一个secureServer。也可以使用 http2 触发其他请求。你可以看看这个article 了解一些想法

    【讨论】:

      【解决方案2】:

      你不会找到 Node.js 的原生方式来:

      如何让下面的代码使用HTTP2来执行请求

      因为,HTTP2 的工作方式与 HTTP1.1 完全不同。 所以Node.js http2核心模块导出的接口完全不同,多了多路复用等特性。

      要使用 HTTP1.1 接口发出 HTTP2 请求,您可以使用 npm 模块,我个人编码并使用: http2-client

      const {request} = require('http2-client');
      const h1Target = 'http://www.example.com/';
      const h2Target = 'https://www.example.com/';
      const req1 = request(h1Target, (res)=>{
          console.log(`
      Url : ${h1Target}
      Status : ${res.statusCode}
      HttpVersion : ${res.httpVersion}
          `);
      });
      req1.end();
      
      const req2 = request(h2Target, (res)=>{
          console.log(`
      Url : ${h2Target}
      Status : ${res.statusCode}
      HttpVersion : ${res.httpVersion}
          `);
      });
      req2.end();
      

      【讨论】:

        猜你喜欢
        • 2021-12-25
        • 2017-08-04
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 2019-11-12
        相关资源
        最近更新 更多