Open In App

How to Generate or Send JSON Data at the Server Side using Node.js ?

Last Updated : 25 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript Object Notation (JSON) is a text-based standard for encoding structured data that is based on JavaScript object syntax. It is extensively used in online applications for data transmission. In this post, we’ll deliver JSON data using a NodeJS server.

JSON Characteristics

  • When compared to XML, it is easier to read and write.
  • JSON is little in size. A JSON string is approximately two-thirds the size of the identical data in XML.
  • A broad range of browsers supports it.
  • JSON saves data in arrays, making data transmission easier. While it is not easy in XML.

Setup and Installation:

Step 1: To start a NodeJS application, create a folder called SendJsonData and run the following command.

npm init -y 

Step 2: Using the following command, install the required npm packages.

npm install express

Step 3: In your project directory, create a file called index.js.

Project Structure: Our project directory should now look like this.

 

Example: The server, which runs on port 3000, is built using the Express framework and NodeJS. You can see a JSON response is sent by the server on the / (home) route.

Javascript




const express = require("express");
const app = express();
app.use(express.json());
  
const data = {
    "name": "vishal",
    "email": "abc@gmail.com"
}
  
app.get("/", function (req, res) {
    res.json(data);
});
  
app.listen(3000, function () {
    console.log("Server started on port 3000");
});


Step to Run the Application: Use the following command to launch the application:

node index.js

Output:

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads