简体   繁体   English

在NodeJS中执行传出HTTP2请求

[英]Performing outgoing HTTP2 requests in NodeJS

I've checked the NodeJS documentation but could not find any information on how to make the following code use HTTP2 to carry out the request: 我已经检查了NodeJS文档,但找不到有关如何使以下代码使用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()

Is this simply not supported yet by even the most recent versions of NodeJS? 甚至最新版本的NodeJS都还不支持此功能吗?

This is available in v9.9.0 . v9.9.0可用。 You can take a look at HTTP2 in Nodejs . 您可以在Nodejs中查看HTTP2 You can create a secureServer in HTTP2 if you want the whole thing. 如果需要整个内容 ,可以在HTTP2中创建一个secureServer Else firing off requests using http2 is available too. 也可以使用http2触发请求。 You can take a look at this article for some ideas 您可以看一下这篇文章中的一些想法

You will not find a Node.js native way to: 您将找不到Node.js本机方式:

how to make the following code use HTTP2 to carry out the request 如何使以下代码使用HTTP2执行请求

Because, HTTP2 works completely different from HTTP1.1. 因为,HTTP2的工作原理与HTTP1.1完全不同。 Therefore, the interface exported by the Node.js http2 core module is completely different, with additional features such as multiplexing. 因此,Node.js http2核心模块导出的接口完全不同,具有多路复用等附加功能。

To make HTTP2 request with the HTTP1.1 interface you can use npm modules, I personally coded and use: http2-client 要使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM