Node.js http.ClientRequest.setHeader() Method
The http.ClientRequest.setHeader() is an inbuilt application programming interface of class ClientRequest within the HTTP module which is used to set the object of the header.
Syntax:
const request.setHeader(name, value)
Parameters: This method takes the name and value of the particular header as a parameter as key-value pair.
Return Value: This method has nothing to return.
Example 1: Filename-index.js
Javascript
const http = require( 'http' );
http.createServer((req, res) => { })
.listen(3000, '127.0.0.1' , () => {
const req = http.request({
port: 3000,
host: '127.0.0.1' ,
});
req.setHeader( 'content-type' , 'text/html' );
console.log( "before operation :- "
+ req.getHeader( 'content-type' ))
req.removeHeader( 'content-type' )
console.log( "after operation :- "
+ req.getHeader( 'content-type' ))
process.exit(0)
});
|
Run the index.js file using the following command:
node index.js
Output:
before operation :- text/html
after operation :- undefined
Example 2: Filename-index.js
Javascript
const http = require( 'http' );
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type' : 'text/plain' });
res.end( 'okay' );
});
server.listen(3000, '127.0.0.1' , () => {
const options = {
port: 3000,
host: '127.0.0.1' ,
headers: {
'Connection' : 'Upgrade' ,
'Upgrade' : 'websocket'
}
};
const req = http.request(options);
req.setHeader( 'Cookie' , [ 'type=ninja' ,
'language=javascript' ]);
console.log( "before operation :- "
+ req.getHeader( 'Cookie' ))
req.removeHeader( 'Cookie' )
console.log( "after operation :- "
+ req.getHeader( 'Cookie' ))
process.exit(0)
});
|
Run the index.js file using the following command:
node index.js
Output:
before operation :- type=ninja,language=javascript
after operation :- undefined
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_setheader_name_value
Last Updated :
05 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...