Node.js: Implement HTTP/2 Get and Put Request Using fetch-h2 Package

In this tutorial, we will introduce how to implement http/2 requests using fetch-h2 package in node.js.

Node.js: Implement HTTP/2 Get and Put Request Using fetch-h2 Package

1.Install fetch-h2 in node.js

npm install fetch-h2

2.Import fetch function of  fetch-h2 in node.js

const { fetch } = require('fetch-h2');

3.Implement http get request

In order ot implement http get request, we can call the fetch function.

fetch("https://nghttp2.org/httpbin/ip", { method: "GET" })
.then(response => {
    console.log(response.status);
    console.log(response.httpVersion);

    return response.text(); 
}) 
.then(text => console.log(text));

Run this code, you may see this result:

node.js http get request

4.Implement http put request

In order to implement put request, we should set body of request.

const { fetch } = require('fetch-h2');

fetch("https://http2.golang.org/ECHO", { method: "PUT", body: "test" })
.then(response => response.text()) 
.then(text => console.log(text));

In this example code, we will send string “text” to server.

Run this code, you will see:

node.js http put string request