简体   繁体   中英

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:

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?

This is available in v9.9.0 . You can take a look at HTTP2 in Nodejs . You can create a secureServer in HTTP2 if you want the whole thing. Else firing off requests using http2 is available too. You can take a look at this article for some ideas

You will not find a Node.js native way to:

how to make the following code use HTTP2 to carry out the request

Because, HTTP2 works completely different from HTTP1.1. Therefore, the interface exported by the Node.js http2 core module is completely different, with additional features such as multiplexing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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