In this tutorial, we will introduce how to implement http/2 requests using fetch-h2 package in node.js.
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:
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: