send(), sendStatus() and json() method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The send() and json() functions are used for sending the response to the client directly from the server. The send() method will send the data in a string format, whereas the json() function will send the same in JSON format. The sendStatus() method is used for sending the HTTP request status with the client. Possible status values are: 200(Success), 404(Not found), 201(Created), 503(Server Unreachable) etc.

Prerequisite

  • Node.js

  • Express.js

Installation

Install the express module using the below statement −

npm install express

Example - sendStatus()

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

node sendStatus.js

sendStatus..js

// Importing the express module
const express = require('express');
const app = express();

// Sending the response for '/' path
app.get('/' , (req,res)=>{
   // Status: 200 (OK)
   res.sendStatus(200);
})

// Setting up the server at port 3000
app.listen(3000 , ()=>{
   console.log("server running");
});

Output

C:\home\node>> node sendStatus.js

And now, hit the following URL from your browser to access the webpage – http://localhost:3000

Example - send()

Create a file with name – send.js and copy the below code snippet. After creating the file, use the below command to run this code as shown in the example below −

node send.js

send.js

// Importing the express module
const express = require('express');
const app = express();

// Initializing the heading with the following string
var heading = "Welcome to TutorialsPoint !";

// Sending the response for '/' path
app.get('/' , (req,res)=>{
   // Sending the heading text
   res.send(heading);
})

// Setting up the server at port 3000
app.listen(3000 , ()=>{
   console.log("server running");
});

Output

C:\home\node>> node send.js

And now, hit the following URL from your browser to access the webpage – http://localhost:3000

Example - json()

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

node json.js

json.js

// Importing the express module
const express = require('express');
const app = express();

// Initializing the data with the following json
var data = {
   portal: "TutorialsPoint",
   tagLine: "SIMPLY LEARNING",
   location: "Hyderabad"
}

// Sending the response for '/' path
app.get('/' , (req,res)=>{

// Sending the data json text
res.json(data);
})

// Setting up the server at port 3000
app.listen(3000 , ()=>{
   console.log("server running");
});

Output

C:\home\node>> node json.js

And now, hit the following URL from your browser to access the webpage – http://localhost:3000

raja
Published on 20-May-2021 13:26:30
Advertisements