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, cookies or 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 = 8080
const 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 HTTP module.

  • In line 3, we define the port number.

  • In line 5, we use http.createServer() to create a server and listen to it on port 8080. We will log our req.headers in the console. req has 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 http request. By default, it is a get request with parameters defined in options.

  • In line 20, using the reference name of request we use request.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 use end(), the request will be made but the server will wait for the the incoming data until end() 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 by server.close(). It will still give you the desired result but with an execution time out error. 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.

Free Resources