How to return JSON using Node.js ?

07 Oct, 2021
JSON stands for JavaScript Object Notation. It is one of the most widely used formats for exchanging information across applications. Node.js Supports various frameworks that help to make the processes smoother. The following ways cover how to return JSON data in our application from Node.js.
Method 1 (Using Express.js):Express is a back end web application framework for Node.js. It is one of the standard frameworks which is used by many developers. To install it, we will be using NPM (Node Package Manager).
Step 1(Installing npm in our directory): To install npm in a project, head over to the terminal and change your current working directory to that project. Then, use the npm init command to initialize the package.json file.$ cd {your-project-directory}
$ npm init
Step 1(Installing npm in our directory): To install npm in a project, head over to the terminal and change your current working directory to that project. Then, use the npm init command to initialize the package.json file.
$ cd {your-project-directory}
$ npm init
Step 2(Installing express): Now that we have npm installed in our project, we can install Express by using the npm install command in our terminal.$ npm install express --save
Step 2(Installing express): Now that we have npm installed in our project, we can install Express by using the npm install command in our terminal.
$ npm install express --save
Step 3(Making express ready for use): After installing express, we can start writing code on our server. We need to require an express module before using it, and we can do that by adding the code given below at the top of our server code.const express = require('express');
const app = express();
Step 3(Making express ready for use): After installing express, we can start writing code on our server. We need to require an express module before using it, and we can do that by adding the code given below at the top of our server code.
const express = require('express');
const app = express();
Step 4(Using express to return JSON data): Now our express is completely ready to use. In the example given below, we are returning data in the following manner:In the ‘/’ route, we are returning an object that contains a single key-value pair.In the ‘/multiple’ route, we are returning an object that contains multiple key-value pairs.In the ‘/array’ route, we are returning an array of objects, each having multiple key-value pairs.
Step 4(Using express to return JSON data): Now our express is completely ready to use. In the example given below, we are returning data in the following manner:
In the ‘/’ route, we are returning an object that contains a single key-value pair.
In the ‘/multiple’ route, we are returning an object that contains multiple key-value pairs.
In the ‘/array’ route, we are returning an array of objects, each having multiple key-value pairs.
Example:
index.js
// Requiring express in our serverconst express = require('express');const app = express();  // Defining get request at '/' routeapp.get('/', function(req, res) {  res.json({    number: 1  });});  // Defining get request at '/multiple' routeapp.get('/multiple', function(req, res) {  res.json({    number: 1,    name: 'John',    gender: 'male'  });});  // Defining get request at '/array' routeapp.get('/array', function(req, res) {  res.json([{      number: 1,      name: 'John',      gender: 'male'    },    {      number: 2,      name: 'Ashley',      gender: 'female'    }  ]);});  // Setting the server to listen at port 3000app.listen(3000, function(req, res) {  console.log("Server is running at port 3000");});
Step to Run Application: Run the application using the following command from the root directory of the project.
node index.js
Output:
Now open your browser and go to http://localhost:3000/, you will see the following output.
Go to http://localhost:3000/multiple, you will see the following output.
Go to http://localhost:3000/array, you will see the following output.
Method 2 (Using HTTP interface): Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node.js and returns JSON data. Node.js comes with an in-built HTTP module, so we won’t have to install it separately as we did for express.
Step 1(Making HTTP ready for use): We need to require HTTP in our server to be able to use it. This can be done simply by adding the code below to our server.var http = require('http');
Step 1(Making HTTP ready for use): We need to require HTTP in our server to be able to use it. This can be done simply by adding the code below to our server.
var http = require('http');
Step 2(Using http and JSON.stringify() to return JSON data): We will now use http.createServer() and JSON.stringify() to return JSON data from our server.
Step 2(Using http and JSON.stringify() to return JSON data): We will now use http.createServer() and JSON.stringify() to return JSON data from our server.
Example:
index.js
var http = require('http');  var app = http.createServer(function(req,res){    res.setHeader('Content-Type', 'application/json');    res.end(JSON.stringify({ number: 1 , name: 'John'}));});  app.listen(3000);
Step to Run Application: Run the application using the following command from the root directory of the project.
node index.js
Output:
Now open your browser and go to http://localhost:3000/, you will see the following output.
Note: Both the methods can be used for returning JSON data from the server and both will produce the same output.
JSON
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React