Node.js http.ServerResponse.headersSent Property
The httpServerResponse.headersSent is an inbuilt application programming interface of class ServerResponse within the HTTP module which is used to check if the header has been sent or not.
Syntax:
const response.headersSent
Parameters: This property does not accept any arguments as a parameter.
Return Value: This property returns true if and only if headers were sent otherwise false.
Example 1: Filename-index.js
Javascript
const http = require( 'http' );
const PORT = process.env.PORT || 3000;
const httpServer = http.createServer(
function (request, response) {
const value = response.headersSent;
response.end( "Headers have been sent : "
+ value, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
});
httpServer.listen(PORT, () => {
console.log( "Server is running at port 3000..." );
});
|
Run the index.js file using the following command:
node index.js
Output:
Server is running at port 3000...
displaying the result...
server is closed
Now open your browser and go to http://localhost:3000/, you will see the following output:
Headers have been sent : false
Example 2: Filename-index.js
Javascript
const http = require( 'http' );
const httpHandlers = (request, response) => {
const value = response.headersSent;
response.end( "Headers have been sent : "
+ value, 'utf8' , () => {
console.log( "displaying the result..." );
httpServer.close(() => {
console.log( "server is closed" )
})
});
};
const httpServer = http.createServer(
httpHandlers).listen(3000, () => {
console.log( "Server is running at port 3000..." );
});
|
Run the index.js file using the following command:
node index.js
Output:
Server is running at port 3000...
displaying the result...
server is closed
Now open your browser and go to http://localhost:3000/, you will see the following output:
Headers have been sent : false
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_headerssent
Last Updated :
06 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...