Node.js response.getHeaders() Method
Last Updated :
15 Sep, 2020
The response.getHeaders() (Added in v7.7.0) method is an inbuilt method of the ‘http’ module which returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the response.getHeaders() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.
In order to get a response and a proper result, we need to import ‘http’ module.
const http = require('http');
Syntax:
response.getHeaders()
Parameters: This property does not accept any parameters.
Return Value <Object>: It returns a shallow copy of the current outgoing headers.
The below examples illustrate the use of response.getHeaders() property in Node.js.
Example: 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( 'Cookie-Setup' ,
[ 'Alfa=Beta' , 'Beta=Romeo' ]);
const headers = response.getHeaders();
console.log(headers);
response.write( 'Hello GeeksforGeeks...' );
response.end();
});
httpServer.listen(PORT, () => {
console.log( "server started at 3000..." )
});
|
Output:
In Console:
>> server started at 3000…
>> [Object: null prototype] {
alfa: ‘Beta’,
‘cookie-setup’: [‘Alfa=Beta’, ‘Beta=Romeo’]}
>> [Object: null prototype] {
alfa: ‘Beta’,
‘cookie-setup’: [‘Alfa=Beta’, ‘Beta=Romeo’]}
Now run http://localhost:3000/ in the browser.
Output: (In Browser)
Hello GeeksforGeeks...
Reference: https://nodejs.org/api/http.html#http_response_getheaders
Share your thoughts in the comments
Please Login to comment...