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.
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.
It takes only one parameter, that is the name of the header that the user wants to remove
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.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)
Line : We import the HTTP
module.
Line : We define the port
number of the server.
Line : We use http.createServer()
to create a server and listen on port 8080
.
Line : We listen to the server using server.listen()
-, and after that, make the request to the callback
function.
Line : We define an object for making a request with options
we want.
Line : We make a HTTP
request using http.request()
. By default this is a get()
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 the name
of 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 use end()
, the request will be made, but the server will wait for the incoming data until end()
is called.
Line : We’ll use setTimeout()
because Educative’s running server feature won’t stop until we stop it by calling 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.