Reading JSON in Model-View-Controller (MVC) applications using Node.js and Express.js

Updated: Jan 26, 2025

Reading JSON in Model-View-Controller (MVC) applications using Node.js and Express.js

To read JSON data in a Model-View-Controller (MVC) application using Node.js and Express.js, follow these steps:

  1. Create a new Node.js project and install Express.js:

First, make sure you have Node.js installed on your system. You can download it from https://nodejs.org/. Once installed, create a new directory for your project and initialize it with npm init. After that, install Express.js by running npm install express --save.

  1. Create an Express.js application:

Create a new file called app.js in your project directory and add the following code to set up a basic Express.js application:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!')
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
});
  1. Read JSON data:

To read JSON data, you can use the built-in fs (File System) module or external libraries like body-parser or express.json. In this example, we will use body-parser for parsing JSON data from requests.

Install body-parser by running npm install body-parser --save. Then, update your app.js file as follows:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.json()); // Middleware for parsing JSON data

app.get('/', (req, res) => {
  res.send('Hello World!')
});

app.post('/api/data', (req, res) => {
  const jsonData = req.body; // Access JSON data from request body
  console.log(jsonData);
  res.send('JSON data received!');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
});

Now, you have an Express.js application that can read JSON data from requests. The JSON data is accessed through the req.body object in the route handler function for the /api/data endpoint.

  1. Test the application:

You can test your application by sending a JSON request using tools like Postman or curl. For example, using Postman, send a POST request to http://localhost:3000/api/data with the following JSON data in the body:

{
  "name": "John Doe",
  "age": 30
}

The application should respond with "JSON data received!". You can also check the console output for the received JSON data.