What is the removeHeader() method in Node.js?
The response.removeHeader() is an inbuilt property of the HTTP module, which removes a header identified by a name that’s queued for implicit sending.
About the method
In this shot, we’ll learn how to remove the header from the HTTP request.
The method request.removeHeader() will be used to remove the header from the request.
Parameter
It takes only one parameter, that is the name of the header that the user wants to remove
Syntax
request.removeHeader(NAME);
NAME: - When we set the header, it takes a name with value. You need to pass that name here to remove the header from the request.
Code
See the following code to remove the header.
const http = require('http')const port = 8080const server = http.createServer((req,res)=>{res.end();});server.listen(port, () => {console.log(`Server running at port ${port}...\n\n`)var options = {port: 8080,host: '127.0.0.1',};var request = http.request(options);request.setHeader('Cookie', ['type=ninja', 'language=javascript']);let header1 = request.getHeader('Cookie');console.log("Before removing the header from the actual request:");console.log("header 1 = ",header1);request.removeHeader('Cookie');header1 = request.getHeader('Cookie');console.log("\n\nAfter removing the header from the actual request:");console.log("header 1 = ",header1);request.end();})setTimeout(()=>{server.close()},2000)
Explanation
-
Line : We import the
HTTPmodule. -
Line : We define the
portnumber of the server. -
Line : We use
http.createServer()to create a server and listen on port8080. -
Line : We listen to the server using
server.listen()-, and after that, make the request to thecallbackfunction. -
Line : We define an object for making a request with
optionswe want. -
Line : We make a
HTTPrequest usinghttp.request(). By default this is aget()request with parameters defined in the options. -
Line , We set the header of the request using
request.setHeader(). -
Line and : We get the header by passing the header
name-, and storing it into a variable. -
Line : We use
request.removeHeader(Name)with thenameof the header we want to remove. -
Line and : We print the header value we got from lines and , to check whether we have successfully removed the header or not.
-
Line :
request.end()is important, as it finishes the request. If we do not useend(), the request will be made, but the server will wait for the incoming data untilend()is called. -
Line : We’ll use
setTimeout()because Educative’s running server feature won’t stop until we stop it by callingserver.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.