How to set headers in request in Node.js
Headers in request
In this shot, we will learn why headers are important while making a request to a server and how to set headers in request.
We will use request.setHeader() to set header of our request.
The header tells the server details about the request such as what type of data the client, user, or request wants in the response.
Type can be
html,text,JSON,cookiesor others.
Syntax
request.setHeader(NAME, VALUE);
-
NAME: This is the first parameter that tells us the name of the header. -
VALUE: This is the second parameter which contains the value of the header it is adding.
Code
const http = require('http')const port = 8080const server = http.createServer((req,res)=>{console.log(req.headers);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');request.end();})setTimeout(()=>{server.close()},2000)
Explanation
-
In line 1, we import the
HTTPmodule. -
In line 3, we define the port number.
-
In line 5, we use
http.createServer()to create a server and listen to it on port8080. We will log ourreq.headersin the console.reqhas the details of incoming requests made to the server. -
In line 10, we create a server that will listen to incoming requests by using
server.listen(). We will make the request after listening to the server. -
In line 13, we define the object for the request with the options we want.
-
In line 18, we make an
httprequest. By default, it is agetrequest with parameters defined inoptions. -
In line 20, using the reference name of
requestwe userequest.setHeader()to define the request header. -
In line 23,
request.end()is important as it finishes the request, meaning the request has all the necessary data it needs to send. If we don’t useend(), the request will be made but the server will wait for the the incoming data untilend()is called. -
In lines 26-28, we are using
setTimeout()because the educative feature of the running server will not stop until we stop it byserver.close(). It will still give you the desired result but with anexecution time outerror. You don’t need to write this on your personal machine.
Result
We have successfully added headers in the request. You can see the output which is an object with the details of the headers.