What is request.getHeader in Node?

In this shot, we will learn how to get the header of a request.

We will use request.getHeader() to get the header of our request. The header tells the server the details of the request. For instance, if the header is a cookie, then the server will work according to that data.

Syntax

request.getHeader(NAME);

Parameters

  • NAME - When we set the header, it has a name with value. We need to pass the name to get the value.
const http = require('http')
const port = 8080
const server = http.createServer((req,res)=>{
res.end();
});
server.listen(port, () => {
console.log(`Server running at port ${port}`)
var options = {
port: 8080,
host: '127.0.0.1',
};
var request = http.request(options);
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
request.setHeader('content-type', 'text/html');
const header1 = request.getHeader('Content-Type');
const header2 = request.getHeader('Cookie');
console.log("header 1 = ",header1);
console.log("header 2 = ",header2);
request.end();
})
setTimeout(()=>{
server.close()
},2000)

Explanation

  • In line 1, we import the HTTP module.

  • In line 3, we define the port number of the server.

  • In line 5, we use http.createServer() to create a server and listen to it on port 8080.

  • In line 9, we use server.listen() to listen to the server and make the request in a callback function.

  • In line 12, we define an object for the request with the desired options.

  • In line 17, we make an http request, which is a get request by default, with the parameters defined in options.

  • In lines 19 and 20, we use request.setHeader() to set the header with a different Name and Value.

  • In lines 22 and 23, we use request.getHeader(Name) to get the value of the header to pass the name of the header in the method.

  • In lines 25 and 26, we print the header value we get from the request.getHeader() function.

  • In line 29, request.end() is important as it finishes the request, meaning the request has all the necessary details/data it needs to get a response. If we don’t use end(), the request will be made, but the server will wait for the incoming data until end() is called.

  • In lines 32-34, we use setTimeout() because the educative feature of the running server will not stop until we call server.close(). The code will still give you the desired result, but with the Execution Timeout error. You don’t need to write this in your personal machine.

Summary

We have successfully retrieved the value of specific headers. You can see the output, which is the same data we set in the header.

Free Resources