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

3

8

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

Contredanse answered 29/9, 2019 at 15:40 Comment(2)
What's the issue with what's built-in? nodejs.org/api/http2.htmlDroopy
Example code can be found in node.js core documentation: nodejs.org/api/http2.html#http2_client_side_examplePresurmise
P
10

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

Patchwork answered 30/9, 2019 at 10:10 Comment(2)
How can i receive all headers?Contredanse
Good answer. You may need to change the content-type header to application/x-www-form-urlencoded, or whatever you need, depending on the backend. The important thing is the content-length and req.end with the body/data to send. By other hand you may need to add cookie support manually on "response" callback through the set-cookie header.Annecy
D
1

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.')
});
Dynamism answered 29/9, 2019 at 18:31 Comment(2)
The first sentence is correct but the rest of the answer is simply not relevant to the question. He's looking for a http2 client, not serverPresurmise
I'm not looking for a HTTP/2.0 server. I'm looking for a way to send a HTTP/2.0 request to google.comContredanse
R
0

Just to add more note cause this is the main point behind using HTTP2 in case you have multiple requests to the same endpoint

var payload1 = JSON.stringify({});
var payload2 = JSON.stringify({});

const client = http2.connect('server url');
const request = client.request({
  ":method": "POST",
  ':path': 'some path',
  'authorization': `bearer ${token}`,
  "content-type": "application/json",
});

request.on('response', (headers, flags) => {
  for (const name in headers) {
    console.log(`${name}: ${headers[name]}`);
  }
});
request.setEncoding('utf8');
let data = ''
request.on('data', (chunk) => { data += chunk; });
request.on('end', () => {
  console.log(`\n${data}`);
  client.close();
});
// send as many request you want and then close the connection
request.write(payload1)
request.write(payload2)
request.end();

Hope to help someone

Radioluminescence answered 21/1, 2023 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.