Open In App

How to return JSON using Node.js ?

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).



Example:




// Requiring express in our server
const express = require('express');
const app = express();
  
// Defining get request at '/' route
app.get('/', function(req, res) {
  res.json({
    number: 1
  });
});
  
// Defining get request at '/multiple' route
app.get('/multiple', function(req, res) {
  res.json({
    number: 1,
    name: 'John',
    gender: 'male'
  });
});
  
// Defining get request at '/array' route
app.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 3000
app.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:

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.

Example:




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.


Article Tags :