Node.js response.getHeaderNames() Method
Last Updated :
15 Sep, 2020
The response.getHeaderNames() (Added in v7.7.0) method is an inbuilt application programming interface of the ‘http‘ module which returns an array containing the unique names of the current outgoing headers. All header names are lowercase.
When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.
In order to get a response and a proper result, we need to import ‘http’ module.
Syntax:
const http = require('http');
Syntax:
response.getHeaderNames()
Parameters: This property does not accept any parameter.
Return Value: It returns the names of all the headers in string format as explained below by Example.
The below example illustrates the use of response.getHeaderNames() Method in Node.js.
Example 1: Filename: index.js
var http = require( 'http' );
const PORT = process.env.PORT || 3000;
var httpServer = http.createServer(
function (req, response) {
response.setHeader( 'Alfa' , 'Beta' );
response.setHeader( 'Foo' , 'bar' );
response.setHeader( 'Set-Cookie' ,
[ 'foo=bar' , 'bar=baz' ]);
const headerNames = response.getHeaderNames();
console.log(headerNames);
response.end( "200, ok" );
});
httpServer.listen(PORT, () => {
console.log(
"Server is running at port 3000..." );
});
|
Output:
Output: In Console
>> Server is running at port 3000…
>> [ ‘alfa’, ‘foo’, ‘set-cookie’ ]
Now run http://localhost:3000/ in the browser.
Output: In Browser
200, ok
Example 2: Filename: index.js
var http = require( 'http' );
const PORT = process.env.PORT || 3000;
var httpServer = http.createServer(
function (req, response) {
response.setHeader( 'Alfa' , 'Beta' );
response.setHeader( 'Alfa1' , '' );
response.setHeader( 'Alfa2' , 5);
response.setHeader( 'Cookie-Setup' ,
[ 'Alfa=Beta' , 'Beta=Romeo' ]);
const headers = response.getHeaders();
const headerNames = response.getHeaderNames();
console.log(headers);
console.log(headerNames);
var Output = "Hello Geeksforgeeks...,"
+ " Available headerNames are:"
+ JSON.stringify(headerNames);
response.write(Output);
response.end( 'ok' );
});
httpServer.listen(PORT, () => {
console.log( "Server is running at port 3000..." );
});
|
Run index.js file using the following command:
node index.js
Output:
Output: In Console
Server is running at port 3000…
>> [Object: null prototype] {
alfa: ‘Beta’,
alfa1: ”,
alfa2: 5,
‘cookie-setup’: [ ‘Alfa=Beta’, ‘Beta=Romeo’ ]}
>> [ ‘alfa’, ‘alfa1’, ‘alfa2’, ‘cookie-setup’ ]
Now run http://localhost:3000/ in the browser.
Output: In Browser
Hello Geeksforgeeks…, Available headers and trailers are:{“alfa1″:””, “cookie-setup”:[“Alfa=Beta”, “Beta=Romeo”],
“content-type”:”text/plain”, “trailer”:”Content-MD5″}ok
Reference: https://nodejs.org/api/http.html#http_response_getheadernames
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...