Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Basic
  • Last Updated : 01 Apr, 2021

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:

  • Node js: It is an open-source JavaScript Back-End technology.
  • Express.js: It is a node.js server framework.

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.



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

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.

index.js




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.

index.js




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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :