Open In App

Model-View-Controller(MVC) architecture for Node applications

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

MVC is an acronym for Model-View-Controller. It is a design pattern for software projects. It is used majorly by Node developers and by C#, Ruby, PHP framework users too. In MVC pattern, application and its development are divided into three interconnected parts. The advantage of this is it helps in focusing on a specific part of the application name, the ways information is presented to and accepted from, the user. It helps in allowing for efficient code reuse and the parallel development of the application. Even if the project structure might look a little different than an ideal MVC structure, the basic program flow in and out the application remains the same. In this post, the program flow between these components of an application will be shown by creating a demo application. First, lets get through with what these parts of the application mean and what functions they perform.

Explanation

Model: Model represents the structure of data, the format and the constraints with which it is stored. It maintains the data of the application. Essentially, it is the database part of the application. View: View is what is presented to the user. Views utilize the Model and present data in a form in which the user wants. A user can also be allowed to make changes to the data presented to the user. They consist of static and dynamic pages which are rendered or sent to the user when the user requests them. Controller:Controller controls the requests of the user and then generates appropriate response which is fed to the viewer. Typically, the user interacts with the View, which in turn generates the appropriate request, this request will be handled by a controller. The controller renders the appropriate view with the model data as a response. So, to sum it up:

  • Model is data part.
  • View is User Interface part.
  • Controller is request-response handler.
mvc architecture

MVC architecture

Now, lets get started with the application. npm init is used here to generate a package.json and app.js file.

npm-init

npm-init

As the name suggests, there are three folders, called models, views, controllers which will help in the mvc architecture implementation. npm is used to install the basic npm packages to get started.

npm-package-install-snip

npm-package-install-snip

The project structure looks like this.

mvc-project-snip

mvc-project-structure snip

Project Structure Explanation

  • As you can see, there is aroutes folder, which will serve as controllers.
  • Then there is a models folder, in which we have a user model.
  • A views folder, which have our views with an extension of .handlebars. Be noted that handlebars is a templating engine which means that it has the ability to generate the pages by filling in the templating that we create.

Now, let’s get down to showing how the MVC pattern gets implemented for the process of login and registering as a user in this demo LoginApp.

  • Write node app.js to start the application. The application will start if everything is right otherwise try to debug the app using stackoverflow and things like that.
  • Open the app in your browser. If you have forked and using my github repo, then navigate to localhost:3000 in your browser and you will see the app running.When you open the app in your browser, your app.js file will say to itself something like :”Oh! The browser has requested localhost:3000/, so lets look for the file to serve if this route is hit. It looks for this code:
app use route appjs

App use route appjs

  • . It tells the app that use the variable routes if ‘/’ is requested. Then it looks for the routes variable. It finds it in the app.js file here:
routes requires

Routes requires

  • . Now it looks in the gfgIndex.js file in the routes folder of our node app to look for the code to execute when the ‘/’ route is hit. It finds the following code.
gfgIndexjs routes file

GfgIndexjs routes file

  • This code basically says that render the index.hanblebars if the user is logged in. To check if the user is logged in, it runs the function ensureAuthenticated. This function basically says that if the user is logged in, render the index.handlebars file else redirect the user to the /users/login route.
gfgUsersjs login route snip

GfgUsersjs login route snip

  • This code tells the app to render the index.handlebars file when the GET ‘/’ is called. So, now it goes to the views folder and look for the index.handlebars and renders it to the user. This is how the views-controller part of the architecture works in the app. I believe the above program flow is clear to the reader.
  • Lets navigate to http://localhost:3000/users/register. So, the app breaks the route into two pieces:/users and /register and asks itself something like “Oh okay! The users wants to see /users route and then /register . The app looks for the ‘/users’ in its app.js file and finds it here.
app use route appjs

App use route appjs

  • . Then it looks for the ‘users’ variable to use when /users path is hit which can be found in the app.js file:
routes requires

Routes requires

  • . So, it goes to the gfgUsers.js file in the routes folder and looks for the route /register. Note that the /users/register finds itself in gfgUsers.js file as /register. It asks the browser to render ‘register.handlebars’ file. This is the view-controller arch. implementation going on. Second Part of Registration Now, lets register a new user.
register a new user snap. image:https://media.geeksforgeeks.org/wp-content/uploads/register-a-new-user-snap.png

Register a new user snap. image:https://media.geeksforgeeks.org/wp-content/uploads/register-a-new-user-snap.png

  • After clicking on submit, the data is taken, POSTed to the ‘/register’ route for processing. This controller validates the incoming data for errors, then creates a new variable called newUser with the User  modelled with all the data and the calls save() on it to actually save the data to the user.
new user console logged into the terminal

New user console logged into the terminal

  • After the user is created, the ‘/register’ controller asks the browser to redirect the user to ‘/login’ page. This is the model-view-controller architecture implementation.

You can find the entire code used in this article here. Fork, clone and run.


Similar Reads

Introduction to Model View View Model (MVVM)
Description of Model is as follows: MODEL: ( Reusable Code – DATA ) Business Objects that encapsulate data and behavior of application domain, Simply hold the data. VIEW: ( Platform Specific Code - USER INTERFACE ) What the user sees, The Formatted data. VIEWMODEL: ( Reusable Code – LOGIC ) Link between Model and View OR It Retrieves data from Mode
3 min read
How can AngularJS controller inherit from another controller in the same Module ?
In the AngularJS Framework, Controller Inheritance allows the controller to inherit the properties, methods, and other kinds of utilities from the other controller in the same module. It is nothing but the inheritance concept of OOP. So, in AngularJS, to perform the controller inheritance, we can use two different approaches, i.e., the $controller
5 min read
How to insert HTML into view from AngularJS controller?
The ng-bind-html directive is a secure way of binding content to an HTML element. So in order to insert HTML into view, we use the respective directive. While using AngularJS, write HTML in our corresponding application, we should check the HTML for dangerous or error prone code. By including the "angular-sanitize.js" module in the application we c
2 min read
Explain basic structure of a MVC model
Models, Views, and Controllers (MVC) patterns are used by CodeIgniter to organized the files. This helps us to maintain the data, the presentation, and flow through the application. To make things more clear we can understand with their basic definition: Models manage the data of the application and help to enforce any special business rules that t
2 min read
Create a Table of Content in Tree View Architecture using HTML, CSS and JavaScript
The tree view elements are a kind of a dropdown menu however well organized. This kind of view gives your website an organized look, to create a tree view architecture of a drop we can use HTML, CSS, and JavaScript. We will divide the whole procedure into two sections Creating structure and Designing structure. Below both sections are elaborated Cr
3 min read
How a View-model works in Vue.js?
Vue.js is a front-end progressive javascript framework for building User Interfaces ( UI ) and Single Page Applications. This framework focuses on Model – View – ViewModel architecture pattern that connects the View ( User Interface ) and the Model ( Data Objects ). Vue.js uses many built-in directives for interacting between View and Model. It hel
4 min read
AngularJS ng-controller Directive
The ng-controller Directive in AngularJS is used to add a controller to the application. It can be used to add methods, functions, and variables that can be called on some event like click, etc to perform certain actions. Syntax: <element ng-controller="expression"> Contents... </element> Parameter value: expression: It refers to the na
2 min read
HTML | DOM Video controller Property
The controller property returns the present media controller of the video. By default, the video element doesn't have a media controller. The media controller property will return a MediaController object. Syntax videoObject.controller Return Value MediaController: It Represent the media controller of video Object: MediaController Object properties
2 min read
HTML | DOM Audio controller Property
The controller property returns the present media controller of the audio. By default, the audio element does not have a media controller. The media controller property will return a MediaController object. Syntax: audioObject.controller Note: This property has been DEPRECATED and is no longer recommended. Return Value: MediaController:It represent
2 min read
How to execute AngularJS controller function on page load ?
In this article, we will see how to execute/call a JS function on page load using AngularJS. This function can be used to perform initialization. Calling a function or initializing a single value on page load in AngularJS is quite easy. AngularJS provides us with a dedicated directive for this specific task. It's the ng-init directive. Syntax: <
2 min read
Article Tags :