Express.js – res.end() Method


The res.end() method ends the current response process. This method is used to quickly end the response without any data. If one needs to respond with data, they should use either the res.send() method or the res.json() method.

Syntax

res.end([data], [encoding])

Default encoding is 'utf-8'.

Example 1

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

// res.end() Method 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
app.get('/api', function (req, res) {
   console.log("Ending the process without any data");
   res.end();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

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

C:\home
ode>> node resEnd.js Server listening on PORT 3000 Ending the process without any data

Example 2

Let's take a look at one more example.

// res.end() Method 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
app.get('/api', function (req, res) {
   console.log("Ending the process without any data");
   res.end();
   res.send("Data sent after ending the process");
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

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

C:\home
ode>> node resEnd.js Server listening on PORT 3000 Ending the process without any data Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (/home/node/test/node_modules/express/lib/response.js:771:10) at ServerResponse.contentType (/home/node/test/node_modules/express/lib/response.js:599:15) at ServerResponse.send (/home/node/test/node_modules/express/lib/response.js:145:14) at /home/node/test/express.js:16:6

Updated on: 06-Apr-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements