Moment For Technology

Express - MVC

Posted on Dec. 3, 2022, 9:21 a.m. by Kathryn Collins
Category: The back-end Tag: The back-end architecture

This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge


How to design the structure of a program, this is a specialized knowledge, called "architectural pattern" (ARCHITECTURAL pattern), belongs to the methodology of programming, MVC pattern is a kind of architectural pattern.

So what is MVC? MVC is a shorthand for three words, Model, View, Controller.

Explain each of them

A View is a View layer directly facing the user. It's the interface that the user operates on. It's the shell of the application

Model The Model is the core data layer and the data that the program needs to operate

Controller The Controller layer between the view and the Model is responsible for retrieving data from the data layer (Model) based on user input from the view layer, and then performing corresponding operations on it - processing database data or returning feedback to the user

These three layers are closely linked, but they are independent of each other, and changes inside each layer do not affect the other layers. Each layer provides an external interface that can be invoked by the layer above. In this way, the software can be modularized, modifying the appearance or changing data without changing the other layers, greatly facilitating maintenance and upgrading

The following Express framework based on specific implementation of a small example based on MVC architecture


As mentioned above, the model is the data layer. Since it is the data layer, the database is indispensable. Here, the operation of mysql database is taken as an example

First of all, this machine to install mysql database services, here do not do too much introduction, you can query the installation method online

Plug-ins that need to be downloaded

Mysql2 database support

Sequelize operates mysql's ORM framework

Async Library of asynchronous processing methods

npm i mysql2
npm i sequelize
npm i async
Copy the code

Create user database

Create user data table

Adding simulation Data

New database configuration file

To make it easier for other files to reference the database object, put the database object instantiation in a separate file, create the database directory under the database directory, and create the index.js file under the database directory and write the following configuration

var Sequelize = require('sequelize') var Config = require('.. Var sequelize = new sequelize ('user', 'root', '12345678',{host: 'localhost', // database type dialect: 'mysql', // whether to print logs logging: true, pool:{Max: 5, min:0, idle: }, // disable all timestamps define: {timestamps: false}, // set timeZone: '+08:00'}) module.exports = sequelizeCopy the code

New model file (ORM database mapping file)

The Object Relational Mapping (ORM) pattern is a technique for resolving the mismatch between object-oriented and Relational databases. In simple terms, ORM automatically persists objects in a program into a relational database by using metadata that describes the mapping between objects and databases

After the database support is installed and the database configuration file is added, you need to create the Models directory under the Model root directory and create the user.js file under the Models directory

const Sequelize = require('sequelize') const db = require('.. /database/index.js') // define model const User = db.define(' User ', Id: {type: Sequelize.INTEGER, primaryKey: true, allowNull: false,autoIncrement:true}, name: {type: Sequelize.STRING(20), allowNull: true}, age: {type: Sequelize.INTEGER(2), allowNull: true}, }) module.exports = UserCopy the code

At this point the Model layer is complete

View the View layer

The view layer is detailed in the next article, see the Express-View section for details

The contents of the new index. HTML in the views directory are as follows

! DOCTYPE html html lang="en" head meta charset="UTF-8" meta http-equiv="X-UA-Compatible" content="IE=edge" meta  name="viewport" content="width=device-width, " titleDocument/title /head body {{item as item}} p . {{item name}} age: {{item. Age}}  / p  {{/ each}}  / body   / HTML Copy the code

Controller Business process control layer

Now, the key part, it says, is that the Controller layer is the bridge between the view and the model

Create a constant directory in the root directory and create status.js

Const status = {SUCCESS: {code:200, MSG :' SUCCESS '}, ERROR:{code: 500, MSG :' SUCCESS '}, }, LACK:{code:403, MSG :' missing parameter '}} module.exports = statusCopy the code

Create the controller directory in the root directory and the user.js controller in the controller directory

The details are as follows

const async = require('async') const UserModel = require('.. /models/user') const Constant = require('.. }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} Cb = {userModel.findall ({limit:10}).then((result) = {// process the data to get the desired field cb(null, = { return {,, age:res.age } })) }).catch((err) = { console.log(err) cb(Constant.ERROR) }) } }, (err, Result) = {if(err){console.log(err)} console.log(result['query']) // Output to view res.render('index', {list:result['query']}) }) } module.exports = exportObjCopy the code

The routing configuration

Import the controller and bind the router address

const user = require('.. /controllers/user') router.get('/user', user.getList)Copy the code

The final result is as follows

That's all for this post, thank you very much for reading here, if this article is good or a little bit of help to you, please like, follow, share, of course, any questions can be discussed in the comments, I will actively answer, thanks again ?

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.