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 = 8080const 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
HTTPmodule. -
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
httprequest, which is agetrequest by default, with the parameters defined inoptions. -
In lines 19 and 20, we use
request.setHeader()to set theheaderwith a differentNameandValue. -
In lines 22 and 23, we use
request.getHeader(Name)to get thevalueof theheaderto pass the name of theheaderin the method. -
In lines 25 and 26, we print the
headervalue we get from therequest.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 useend(), the request will be made, but the server will wait for the incoming data untilend()is called. -
In lines 32-34, we use
setTimeout()because the educative feature of the running server will not stop until we callserver.close(). The code will still give you the desired result, but with theExecution Timeouterror. 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.