ReasonJun

Express.js : MVC Pattern 본문

Backend/Express.js

Express.js : MVC Pattern

ReasonJun 2023. 9. 4. 15:57
728x90

 

The MVC pattern in Express.js is a software design pattern that separates an application into three interconnected parts: the model, the view, and the controller.

  • The model is responsible for storing and retrieving data.
  • The view is responsible for presenting the data to the user.
  • The controller is responsible for handling user requests and updating the model.

The MVC pattern is a popular choice for building web applications because it promotes code reuse, modularity, and testability.

Here is an example of how the MVC pattern can be implemented in Express.js:

const express = require('express');
const router = express.Router();

// Model
const User = require('./models/user');

// View
const indexView = require('./views/index');

// Controller
router.get('/', (req, res) => {
  // Get all users from the database
  const users = User.find();

  // Render the index view with the users
  res.render('index', { users });
});

app.use('/', router);

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, the User model is responsible for storing and retrieving user data. The indexView view is responsible for rendering the index page, which displays a list of all users. The indexController controller handles requests to the / route and renders the index view with the list of users.

 

The MVC pattern can be used to build any type of web application, but it is especially well-suited for building complex applications with a lot of functionality.

 

Here are some of the benefits of using the MVC pattern in Express.js:

  • Code reuse: The model, view, and controller can be reused in different parts of the application.
  • Modularity: The model, view, and controller can be easily separated into different files, which makes the code easier to maintain and update.
  • Testability: The model, view, and controller can be easily tested independently, which makes it easier to find and fix bugs.

 

728x90

'Backend > Express.js' 카테고리의 다른 글

Express.js : Middleware  (0) 2023.09.04
Express.js : res.end() / res.send()  (0) 2023.09.04
Express.js : res.json() / res.send()  (0) 2023.09.04
Express.js : Concept  (0) 2023.09.04
Comments