Node.js http.ServerResponse.getHeader() Method
Last Updated :
05 Apr, 2023
The httpServerResponse.getHeader() is an inbuilt application programming interface of the class Server Response within http module which is used to get the response header of the particular name.
Syntax:
response.getHeader(name)
Parameters: This method accepts the name of the header as the parameter.
Return Value: This method returns the value of the particular header object.
Example 1: Filename: index.js
JavaScript
// Node.js program to demonstrate the
// response.getHeader(name) APi
// Importing http module
const http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
const httpServer = http.createServer(
function (request, response) {
// Getting header value
// by using response.getHeader(name) Api
const value = response.getHeaders();
// Display the header value
console.log(value)
// Display result
response.end("hello world ", 'utf8', () => {
console.log("displaying the result...");
// Closing the server
httpServer.close(() => {
console.log("server is closed")
})
});
});
// Listening to http Server
httpServer.listen(PORT, () => {
console.log("Server is running at port 3000...");
});
Steps to run:
node index.js
Console output:
Server is running at port 3000...
[Object: null prototype] {}
displaying the result...
[Object: null prototype] {}
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
hello world
Example 2: Filename: index.js
JavaScript
// Node.js program to demonstrate the
// response.getHeader(name) APi
// Importing http module
const http = require('http');
// Request and response handler
const http2Handlers = (request, response) => {
// Setting the response header
response.setHeader('Content-Type', 'text/html');
// Getting header
// by using response.getHeader() Api
const value = response.getHeader('Content-Type');
// Display result
response.end("header value : "
+ value, 'utf8', () => {
console.log("displaying the result...");
// Closing the server
httpServer.close(() => {
console.log("server is closed")
})
});
};
// Creating http Server and listening
// on the 3000 port
const httpServer = http.createServer(
http2Handlers).listen(3000, () => {
console.log("Server is running at port 3000...");
});
Steps to run:
node index.js
Console output:
Server is running at port 3000...
[Object: null prototype] {}
displaying the result...
[Object: null prototype] {}
displaying the result...
server is closed
server is closed
Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser.
header value : text/html
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_getheader_name