Express.js – res.headersSent Property


res.headersSent returns a Boolean value that indicates if the app has sent HTTP headers for the response or not. If the headers are sent, it returns True; else False.

Syntax

res.headersSent

Example 1

Create a file with the name "headersSent.js" and copy the following code snippet. After creating the file, use the command "node headersSent.js" to run this code as shown in the example below −

// res.headersSent Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint and checking headers
app.get('/api', function (req, res) {
   // Checking the headers before sending response
   console.log(res.headersSent);
   res.send('Welcome To TutorialsPoint');
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request – localhost:3000/api

Output

C:\home
ode>> node headersSent.js Server listening on PORT 3000 false

Example 2

Let's take a look at one more example.

// res.headersSent Property Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint and checking headers
app.get('/api', function (req, res) {
   // Checking the headers before sending response
   console.log(res.headersSent);
   res.send('Welcome To TutorialsPoint');
   // Checking the headers after sending response
   console.log("Headers Sent: ", res.headersSent);
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET Request – localhost:3000/api

Output

C:\home
ode>> node headersSent.js Server listening on PORT 3000 false Headers Sent: true

Updated on: 28-Mar-2022

660 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements