Skip to content
Related Articles

Related Articles

Node.js http.ServerResponse.headersSent Property
  • Last Updated : 12 Jan, 2021

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




// Node.js program to demonstrate the  
// response.headersSent() method
  
// Importing http module 
var http = require('http');
  
// Setting up PORT 
const PORT = process.env.PORT || 3000;
  
// Creating http Server 
var httpServer = http.createServer(
    function (request, response) {
  
    // Checking if response header is sent or not
    // by using headersSent method
    const value = response.headersSent;
  
    // Display result by using end() method
    response.end("Headers have been sent : "
                   + value, 'utf8', () => {
        console.log("displaying the result...");
  
        httpServer.close(() => {
            console.log("server is closed")
        })
    });
});
  
// Listening to http Server 
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




// Node.js program to demonstrate the  
// response.headersSent() method
  
// Importing http module 
var http = require('http');
  
// Request and response handler 
const httpHandlers = (request, response) => {
  
    // Checking if response header is sent or not
    // by using headersSent method
    const value = response.headersSent;
  
    // Display result by using end() method
    response.end("Headers have been sent : "
                      + value, 'utf8', () => {
        console.log("displaying the result...");
  
        httpServer.close(() => {
            console.log("server is closed")
        })
    });
};
  
// Creating http Server 
var 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :