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:
- 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:
- Using send() function.
- 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)=>{
res.status().send(200);
})
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)=>{
res.send(computerSciencePortal);
})
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();
var data = {
portal : "GeeksforGeeks" ,
knowledge : "unlimited" ,
location : "Noida"
}
app.get( '/' , (req,res)=>{
res.json(data);
})
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.
Last Updated :
06 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...