Open In App

How to send response from server to client using Node.js and Express.js ?

The following approach covers how to send responses from servers using node and express. Also, we are going to see different ways to send responses from the server to the client.

Prerequisite:



Required Module: Install the express module using the following command:

npm install express

Methods to send response from server to client are:



  1. Using send() function.
  2. Using json() function.

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




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");
});

Run the index.js file using the following command:

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.




const express = require('express');
const app = express();
  
var computerSciencePortal = "GeeksforGeeks";
  
app.get('/' , (req,res)=>{
   // Server will send GeeksforGeeks as response
   res.send(computerSciencePortal); 
})
  
// Server setup
app.listen(4000 , ()=>{
    console.log("server running");
});

Run the index.js file using the following command:

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.




const express = require('express');
const app = express();
  
// Sample JSON data
var data = {
    portal : "GeeksforGeeks",
    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");
});

Run the index.js file using the following command:

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.


Article Tags :