Reading JSON in Model-View-Controller (MVC) architecture
JSON (JavaScript Object Notation) is a popular data format used for transmitting data between a client and a server. In the context of Model-View-Controller (MVC) architecture, JSON data is often used to transfer data from the model to the view for rendering. In this answer, we will discuss how to read JSON data in an MVC application using Node.js and Express.js.
First, let's create a simple Express.js application. We will create a route that returns a JSON response when requested.
const express = require('express');
const app = express();
const port = 3000;
app.get('/api/data', (req, res) => {
const data = { message: 'Hello, World!', users: [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }] };
res.json(data);
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
In this example, we define a route /api/data
that returns a JSON object containing a message and an array of users. When a request is made to this route, the server responds with the JSON data.
Now, let's create a view that can display this data. We will use EJS (Embedded JavaScript Templates) as our view engine.
const path = require('path');
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.get('/', (req, res) => {
res.render('index', { data: req.app.locals.data });
});
In this example, we set the view engine to EJS and set the views directory. We also define a route /
that renders the index.ejs
template and passes the JSON data to the template as a local variable.
Finally, let's create the index.ejs
template that can display the JSON data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MVC JSON Example</title>
</head>
<body>
<h1><%= data.message %></h1>
<ul>
<% data.users.forEach(user => { %>
<li><%= user.name %> is <%= user.age %> years old.</li>
<% }); %>
</ul>
</body>
</html>
In this example, we use Embedded JavaScript to display the message and iterate over the users array to display each user's name and age.
When you run the application and navigate to the root URL, you should see the following output:
Server listening at http://localhost:3000
Hello, World!
Alice is 25 years old.
Bob is 30 years old.
This is a simple example of how to read JSON data in an MVC application using Node.js and Express.js. The JSON data is returned from the model (in this case, the Express.js route), passed to the view (in this case, an EJS template), and displayed to the user.