How to Send Response From Server to Client using Node.js and Express.js ?

In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. This article will guide you through the process of sending different types of responses from a server to a client using Node.js and Express.js.

Prerequisite:

Installation Steps

Step 1: Create a new directory for your project and initialize it with npm:

mkdir myapp
cd myapp
npm init -y

Step 2: Install the necessary packages/libraries in your project using the following commands.

npm install express

Project structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.19.2",
}

Sending Different Types of Responses

1. Sending Plain Text

You can send plain text using the res.send method. This method is versatile and automatically sets the Content-Type header to text/plain for strings.

app.get('/text', (req, res) => {
res.send('Hello, this is a plain text response!');
});

2. Sending HTML

To send HTML content, you can also use res.send. Express will set the Content-Type to text/html when it detects HTML content.

app.get('/html', (req, res) => {
res.send('<h1>Hello, this is an HTML response!</h1><p>Welcome to the world of Express.js.</p>');
});

3. Sending JSON

Sending JSON data is straightforward with res.json. This method sets the Content-Type header to application/json automatically and stringifies the object.

app.get('/json', (req, res) => {
res.json({ message: 'Hello, this is a JSON response!', status: 'success' });
});

4. Sending a File

To send a file, use the res.sendFile method. This method requires an absolute path to the file you want to send.

const path = require('path');

app.get('/file', (req, res) => {
res.sendFile(path.join(__dirname, 'example.txt'));
});

Sending Status Codes

You can set custom status codes using res.status. This method allows you to send a specific HTTP status code along with your response.

app.get('/status', (req, res) => {
res.status(404).send('Page not found');
});

Example 1: Demonstrating the use of the status() function.

Node
// Filename - index.js 

const express = require('express');
const app = express();

app.get('/' , (req,res)=>{
   // 200 status code means OK
   res.status().send(200); 
})

// Server setup
app.listen(4000 , ()=>{
    console.log("server running");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output: Now open your browser and go to http://localhost:4000/, you will see the following output:

Example 2: Sending some particular data to the client then you can use send() function.

Node
// index.js

const express = require('express');
const app = express();

var computerSciencePortal = "w3wiki";

app.get('/' , (req,res)=>{
   // Server will send w3wiki as response
   res.send(computerSciencePortal); 
})

// Server setup
app.listen(4000 , ()=>{
    console.log("server running");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output: Now open your browser and go to http://localhost:4000/, you will see the following output:

Example 3: Sending the JSON response from the server to the client using json() function.

Node
// index.js

const express = require('express');
const app = express();

// Sample JSON data
var data = {
    portal : "w3wiki",
    knowledge : "unlimited",
    location : "Noida"  
}

app.get('/' , (req,res)=>{
   // This will send the JSON data to the client.
    res.json(data); 
})

// Server setup
app.listen(4000 , ()=>{
    console.log("server running");
});

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output: Now open your browser and go to http://localhost:4000/, you will see the following output:

So, These are the methods that you can use to send responses from server to client using node and express.

Key Points Recap:

  • Use res.send for plain text or HTML.
  • Use res.json for JSON responses.
  • Use res.sendFile to send files.
  • Use res.redirect to redirect the client.
  • Use res.status to send specific HTTP status codes.
  • Handle errors and asynchronous operations appropriately.
  • Organize routes and middleware for cleaner code.

Conclusion

Sending responses from a server to a client using Node.js and Express.js is a fundamental skill in web development. Express simplifies this task with a range of methods that handle various types of responses, from plain text and JSON to file streams and redirects. By understanding how to use these methods effectively, you can build dynamic and interactive web applications that provide a seamless user experience.