The Wayback Machine - https://web.archive.org/web/20240912173119/https://www.geeksforgeeks.org/node-js-clienthttp2session-request-method/
Open In App

Node.js clienthttp2session.request() Method

Last Updated : 06 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The clienthttp2session.request() is an inbuilt application programming interface of class ClientHttp2Session within http2 module which is used to return the object of ClientHttp2Stream.

Syntax:

const clienthttp2session.request(headers[, options])

Parameters: This method takes the following argument as a parameter.

  • header: Header object.
  • options: It takes any of the arguments {endStream, exclusive, parent, weight, waitForTrailers}

Return Value: This method returns the object of ClientHttp2Stream.

How to generate private key and public certificate?

Private key:

Step — 1: Open notepad and copy and paste the following key.

-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC38R9wXcUbhOd44FavgmE5R3K4JeYOHLnI7dUq1B8/Gv7l3SOg
JKef/m9gM1KvUx951mapXGtcWgwB08J3vUE2YOZ4tWJArrVZES0BI/RmFAyhQFP5
HcWl3LSM9LRihP98F33oIkKaCxA5LxOrkgpV4HrUzIKTABDYah7RPex1WQIDAQAB
AoGBAIXR71xxa9gUfc5L7+TqBs+EMmrUb6Vusp8CoGXzQvRHMJCMrMFySV0131Nu
o0YYRDsAh1nJefYLMNcXd1BjqI+qY8IeRsxaY+9CB2KKGVVDO2uLdurdC2ZdlWXT
Vwr3dDoyR0trnXJMmH2ijTeO6bush8HuXxvxJBjvEllM5QYxAkEA3jwny9JP+RFu
0rkqPBe/wi5pXpPl7PUtdNAGrh6S5958wUoR4f9bvwmTBv1nQzExKWu4EIp+7vjJ
fBeRZhnBvQJBANPjjge8418PS9zAFyKlITq6cxmM4gOWeveQZwXVNvav0NH+OKdQ
sZnnDiG26JWmnD/B8Audu97LcxjxcWI8Jc0CQEYA5PhLU229lA9EzI0JXhoozIBC
TlcKFDuLm88VSmlHqDyqvF9YNOpEdc/p2rFLuZS2ndB4D+vu6mjwc5iZ3HECQCxy
GBHRclQ3Ti9w76lpv+2kvI4IekRMZWDWnnWfwta+DGxwCgw2pfpleBZkWqdBepb5
JFQbcxQJ0wvRYXo8qaUCQQCgTvWswBj6OTP7LTvBlU1teAN2Lnrk/N5AYHZIXW6m
nUG9lYvH7DztWDTioXMrruPF7bdXfZOVJD8t0I4OUzvC
-----END RSA PRIVATE KEY-----

Step — 2: Save as private-key.pem

Public certificate

Step — 1: Open notepad and copy and paste the following key

-----BEGIN CERTIFICATE-----
MIICfzCCAegCCQDxxeXw914Y2DANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMC
SU4xEzARBgNVBAgMCldlc3RiZW5nYWwxEDAOBgNVBAcMB0tvbGthdGExFDASBgNV
BAoMC1BhbmNvLCBJbmMuMRUwEwYDVQQDDAxSb2hpdCBQcmFzYWQxIDAeBgkqhkiG
9w0BCQEWEXJvZm9mb2ZAZ21haWwuY29tMB4XDTIwMDkwOTA1NTExN1oXDTIwMTAw
OTA1NTExN1owgYMxCzAJBgNVBAYTAklOMRMwEQYDVQQIDApXZXN0YmVuZ2FsMRAw
DgYDVQQHDAdLb2xrYXRhMRQwEgYDVQQKDAtQYW5jbywgSW5jLjEVMBMGA1UEAwwM
Um9oaXQgUHJhc2FkMSAwHgYJKoZIhvcNAQkBFhFyb2ZvZm9mQGdtYWlsLmNvbTCB
nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAt/EfcF3FG4TneOBWr4JhOUdyuCXm
Dhy5yO3VKtQfPxr+5d0joCSnn/5vYDNSr1MfedZmqVxrXFoMAdPCd71BNmDmeLVi
QK61WREtASP0ZhQMoUBT+R3Fpdy0jPS0YoT/fBd96CJCmgsQOS8Tq5IKVeB61MyC
kwAQ2Goe0T3sdVkCAwEAATANBgkqhkiG9w0BAQsFAAOBgQATe6ixdAjoV7BSHgRX
bXM2+IZLq8kq3s7ck0EZrRVhsivutcaZwDXRCCinB+OlPedbzXwNZGvVX0nwPYHG
BfiXwdiuZeVJ88ni6Fm6RhoPtu2QF1UExfBvSXuMBgR+evp+e3QadNpGx6Ppl1aC
hWF6W2H9+MAlU7yvtmCQQuZmfQ==
-----END CERTIFICATE-----

Step — 2: Save as public-cert.pem

Example 1: Filename: index.js

Javascript




// Node.js program to demonstrate the
// clienthttp2session.request() method
const http2 = require('http2');
const fs = require('fs');
 
// Private key and public certificate
// for access
const options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('public-cert.pem'),
};
 
// Creating and initializing server
// by using http2.createServer() method
const server = http2.createServer(options);
 
server.on('session', (session) => {
 
  // Set origin frame
  session.origin('http://localhost:8000');
  console.log("ORIGIN frame is submitted")
});
 
 
server.on('stream', (stream, requestHeaders) => {
 
  // Setting response header to client
  // by using respond() method
  stream.respond({
    ':status': 200,
    'content-type': 'text/plain'
  });
   
  stream.write('hello ');
 
   // Checking if header is sent or not
   // by using pushAllowed method
   const status = stream.pushAllowed;
 
   if(status)
     stream.end("push stream is accepted");
   else
     stream.end("push stream is not accepted");
 
  // Stopping the server by using the
  // close() method
  server.close(()=>{
    console.log("server destroyed");
  })
});
 
server.listen(8000);
 
// Creating and initializing client by
// using tls.connect() method
const client = http2.connect(
 
 
// Getting object of ClientHttp2Stream
// by using request() method
const req = client.request({
  ':method': 'GET',
  ':path': '/'
});
 
req.on('response', (responseHeaders) => {
   
  console.log("status : "
    + responseHeaders[":status"]);
});
 
req.on('data', (data) => {
 
  console.log('Received: %s ',
          data.toString().replace(/(\n)/gm,""));
});
 
req.on('end', () => {
  client.close(()=>{
    console.log("client destroyed");
  })
});


Output:

ORIGIN frame is submitted
status : 200
Received: hello
Received: push stream is accepted
client destroyed
server destroyed

Run the index.js file using the following command:

node index.js

Example 2: Filename: index.js

Javascript




// Node.js program to demonstrate the
// clienthttp2session.request() method
const http2 = require('http2');
const fs = require('fs');
 
// Private key and public certificate
// for access
const options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('public-cert.pem'),
};
 
// Creating and initializing server
// by using http2.createServer() method
const server = http2.createServer(options);
 
server.on('stream', (stream, requestHeaders) => {
 
  // Setting response header to client
  // by using respond() method
  stream.respond({
    ':status': 200,
    'content-type': 'text/plain'
  });
   
  stream.write('hello ');
 
  const session = stream.session;
 
  // Set origin frame
  session.origin('http://localhost:8000');
  stream.end("ORIGIN frame is submitted")
 
  // Stopping the server by using
  // the close() method
  server.close(()=>{
    console.log("server destroyed");
  })
});
server.listen(8000);
 
// Creating and initializing client
// by using tls.connect() method
const client = http2.connect(
 
// Getting object of ClientHttp2Stream
// by using request() method
const req = client.request({
  ':method': 'GET',
  ':path': '/'
});
 
req.on('response', (responseHeaders) => {
   
  console.log("status : "
    + responseHeaders[":status"]);
});
 
req.on('data', (data) => {
 
  console.log('Received: %s ',
    data.toString().replace(/(\n)/gm,""));
});
 
req.on('end', () => {
  client.close(()=>{
    console.log("client destroyed");
  })
});


Output:

status : 200
Received: hello
Received: ORIGIN frame is submitted
client destroyed
server destroyed

Run the index.js file using the following command:

node index.js

Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http2.html#http2_clienthttp2session_request_headers_options



Previous Article
Next Article

Similar Reads

HTTP Request vs HapiJS Request in Node.js
Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end serv
3 min read
How to Detect AJAX Request to Normal Request in Node.js ?
When developing web applications with Node.js, you often need to differentiate between AJAX (Asynchronous JavaScript and XML) requests and normal HTTP requests. AJAX requests are typically used to fetch data without reloading the entire page, while normal requests often result in full page loads. Detecting the type of request can help you tailor th
3 min read
Pre-request and Post-request scripts in Postman
Postman is a powerful tool for testing APIs, and its pre-request and post-request scripts allow you to customize requests and responses. it is an API(utility programming interface) development device that enables construction, taking a look at and altering APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environ
4 min read
How To Fix 400 Bad Request: Request Header Or Cookie Too Large?
Have you ever seen a "400 Bad Request" error while browsing on the web, that might be confusing for you about what it means? When you request to a website the server responds with an HTTP status code. This error is among the responses in terms of the HTTP status code used by web servers in order to communicate with your browser. HTTP Status Codes t
7 min read
Node.js Request Module
The request module is used to make HTTP calls. It is the simplest way of making HTTP calls in node.js using this request module. It follows redirects by default. Note: As of Feb 11th, 2020, the request is fully deprecated. Feature of Request module: It is easy to get started and easy to use.It is a widely used and popular module for making HTTP cal
2 min read
Node.js https.request() Function
Node.js provides two core modules for making http requests. The http module can be used to make http requests and the https module can be used to make https requests. One great feature of the request is that it provides a single module that can make both http and https requests. Feature of https module: It is easy to get started and easy to use. It
1 min read
Node.js request.socket Property
The request.socket (Added in v0.3.0) property is an inbuilt property of the ‘http’ module which references to the underlying socket and most users don't get access to this property. Particularly, the socket doesn't emit 'readable' events but, the socket could be accessed via request.connection. This property guarantees to being an instance of the
3 min read
Node.js request.writableEnded Property
The request.writableEnded (Added in v12.9.0) property is an inbuilt property of the ‘http’ module which returns true after request.end() has been called. This property does not indicate whether the data has been flushed, for this use request.writableFinished instead. In order to get a response and a proper result, we need to import ‘http’ module. S
2 min read
How to create different post request using Node.js ?
A POST request is one of the important requests in all HTTP requests. This request is used for storing the data on the WebServer. For Eg File uploading is a common example of a post request. There are many approached to perform an HTTP POST request in Node.js. Various open-source libraries are also available for performing any kind of HTTP request.
3 min read
Different types of module used for performing HTTP Request and Response in Node.js
HTTP's requests and responses are the main fundamental block of the World Wide Web. There are many approaches to perform an HTTP request and Response in Node.js. Various open-source libraries are also available for performing any kind of HTTP request and Response. An HTTP request is meant to either retrieve data from a specified URI or to push data
3 min read
How to limit the number of documents in a MongoDB request in Node.js ?
Say you are working on a quiz API, with which anybody on the web can fetch random questions based on the defined category. You are done with your API and it has passed all test parameters, now for sake of users you want to add a feature that will let users decide how many questions they want to address and your API will provide them with that amoun
5 min read
What are Request and Cheerio in Node.js NPM ?
In this article, we are going to learn about that request and the cheerio library of node.js with their installation. Request Library: The request module is a very popular library in node.js. It helps in sending the request to the external web application to make the conversation between the client and the server by using the HTTP request. HTTP(or
3 min read
Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request ?
In this article, we will see how to handle the 'error' event that is emitted on 'http.IncomingMessage' in a node.js http.request. In Node.js, the 'http.IncomingMessage' object is used to represent the incoming HTTP request message. This object is a readable stream, and it can emit various events such as 'data', 'end', and 'error'. One of the events
3 min read
Creating Your Own Node HTTP Request Router
In Node, if we want to build our own custom HTTP request router then we can create it by handling the incoming requests and directing them to the specific endpoints. Using this routing process, allows us to define the different actions or responses that are based on the requested URLs. In this article, we will create our own node HTTP request route
2 min read
HTTP headers | Access-Control-Request-Method
The HTTP headers Access-Control-Request-Method is a request type header which has been used to inform the server that which HTTP method will be used when the actual request is made. Syntax: Access-Control-Request-Method: <method> Directives: This header accept a single directive which is mentioned above and described below: <method>: Th
1 min read
Explain the common methods of sending request to a server in jQuery
In this article, we will see the common methods of sending requests to a server by using the jQuery library. jQuery is an open-source JavaScript library jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animation, Ajax interactions cross-browser JavaScript development. Common methods of Sending Requests to the
3 min read
HTTP headers | Access-Control-Request-Headers
Access-Control-Request-Headers is a request-type header used by browsers that contains information about the different HTTP headers that will be sent by the client in the ensuing request. Whenever a client initiates a request to a server, the browser checks if the request needs a CORS preflight or not. In case a CORS preflight request is required,
2 min read
Simple POST request using the fetch API
The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API Syntax: fetch(url, { config }) .then(res => { // Handle response }) .catch(err =
2 min read
DELETE request using XMLHttpRequest by making Custom HTTP library
The task here is to show how the XMLHttpRequest can be used to DELETE data to an API by making a custom HTTP library. A placeholder API that contains an array of objects would be used as an example. The DELETE request is performed on this API. The URL of the API is https://jsonplaceholder.typicode.com/posts/ Prerequisites: Basic knowledge of HTML,
3 min read
Difference between PUT and DELETE request in Vanilla JavaScript
PUT and DELETE are the two different types of HTTP request methods. HTTP protocol supports many methods to transfer data from the server or do any operation on the server. The HTTP protocol supports the following methods, e.g. GET, POST, PUT, DELETE, PATCH, COPY, HEAD, OPTIONS, etc. Before we dive into the main difference between PUT and DELETE req
3 min read
Get request using AJAX by making Custom HTTP library
The task is to show how the XMLHttpRequest can be used to get data from an API by making custom HTTP library. I will be taking a fake API that will contain an array of objects as an example and from that API, we will show to get data by XMLHttpRequest method by making a custom HTTP library. API link: https://jsonplaceholder.typicode.com/posts What
3 min read
POST request using AJAX by making Custom HTTP library
The task is to show how the XMLHttpRequest can be used to POST data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to POST data by XMLHttpRequest method by making a custom HTTP library. Used API: https://jsonplaceholder.typicode.com/posts What is
4 min read
How to make PUT request using XMLHttpRequest by making Custom HTTP library ?
The task is to show how the XMLHttpRequest can be used to PUT/Update data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to PUT data by XMLHttpRequest method by making a custom HTTP library.Used API: https://jsonplaceholder.typicode.com/posts/5Wh
3 min read
Difference between GET and POST request in Vanilla JavaScript
In this article, we will learn about the GET & POST request method in vanilla Javascript, & will also understand these 2 methods through the examples. GET and POST is two different types of HTTP request methods. HTTP protocol supports many methods to transfer data from the server or perform any operation on the server. The HTTP protocol sup
3 min read
How to make simple PUT request using fetch API by making custom HTTP library ?
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update data by fetch API method by making custom HTTP library. The API used in this tutorial is: https:
2 min read
Simple DELETE request using fetch API by making custom HTTP library
Why fetch() API method is used? The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API use
2 min read
ASP Request.QueryString Collection
The ASP Request.QueryString Collection is used to get the value of the variable that will be stored in the HTTP query string from the URL. The Query string is a part of the URL that begins with a question mark (?). Generally, it contains the information of the user. <a href= "geek.asp?txt=this is a query string test">Link with a query string
1 min read
ASP Request.Cookies Collection
Basically Cookies are small files that are stored on a user’s computer. They are used to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or by the client computer. The Request.Cookies Collection is used for returning the value of the collection of the cookies. If the specified co
2 min read
ASP Request.Form Collection
The Request.Form Collection in ASP is used for returning the collection of form elements that posted to the HTTP request body, with a form using the POST method. Syntax Request.Form( element )[(index)|.Count] Parameter: Element: It specifies the name of the form elements. It is a required attribute.Index: It is an optional parameter that represents
1 min read
Postman - Working, HTTP Request & Responses
API...Application Programming Interface... If you're a developer then this word is nothing new for you... Being a developer, you know the importance of API in any kind of application. In simple terms, API is a defined set of rules with some defined methods of communication. With the help of API, software components can interact with each other. You
5 min read