Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a HTTP/2.0 request with node.js

How can i send a httpVersion 2.0 request in nodejs?

I have tried almost every request module there is, and all of them is httpVersion 1.1

like image 283
Hobey823 Avatar asked Sep 29 '19 15:09

Hobey823


2 Answers

Get request:

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 Request

     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)

For more details pls see this official documents: https://nodejs.org/api/http2.html#http2_client_side_example

like image 191
Sandeep Patel Avatar answered Nov 15 '22 03:11

Sandeep Patel


Since Node.js 8.4.0, you can use built-in http2 module to implement an http2 server. Or if you want to use http2 with Express, here's a great module on npm: spdy.

Here're some code from express-spdy:

const fs = require('fs');
const path = require('path');
const express = require('express');
const spdy = require('spdy');

const CERTS_ROOT = '../../certs/';

const app = express();

app.use(express.static('static'));

const config = {
    cert: fs.readFileSync(path.resolve(CERTS_ROOT, 'server.crt')),
    key: fs.readFileSync(path.resolve(CERTS_ROOT, 'server.key')),
};

spdy.createServer(config, app).listen(3000, (err) => {
    if (err) {
        console.error('An error occured', error);
        return;
    }

    console.log('Server listening on https://localhost:3000.')
});
like image 39
Dat Le Avatar answered Nov 15 '22 04:11

Dat Le