Share
Explore

s24 MCOO1003 Assignment 2 The MVC Web App

How to submit this work:

Make a Word Document - Name it as studentName_StudentID.docx
Copy all your code into that Word Document, labelling it according to what section it is for.
Include several screen shots showing your Visual Studio Code and Web Browser displaying the operation of your Application.
Upload this Word Document to:

What are all the technologies introduced in this Lab:
Node.js : To run JavaScript programs on the Server
: To provide the Library Packages for our Program
Visual Studio Code : VSC is written in Node.js using and Package called Electron
Packages
Express
MONGODB
BodyParser to work with HMTL Forms
Handlebars


Working on the Server-side (Your own computer in this case):

This is all stuff goingo on in the “Server Side” under Node.js
You will be setting up a number of Servers:
expressjs : WEB Server
mongodb : Database Server

megaphone
We talked about the Controller in MVC.
Basic JavaScript coding is how we implement the Controller.

Basics of any Programming Language with Examples from JavaScript


Any programming language has 2 structuring elements:
Volatile Variables (storage data inside the program) : Live only as long as the duration of the program run. Then dissolve and go away.
Flow of Control: There are 4 kinds of Flow of Conrol:
variable assignment and comparison
If then, branching
Loops, repetition
reusable blocks of code [functions, objects]
I'll create a code drills lab to teach these fundamental programming concepts using JavaScript.
This lab will help students who are new to JavaScript and programming in general.

JavaScript Fundamentals Code Drills Lab

Note: JavaScript is NOT strongly typed Object Oriented like Java.
JavaScript uses inferencial (guessing) typing based on the variable provided.
Objective: To introduce basic programming concepts using JavaScript.
Part 1: Variables and Data Types
1.1 Declaring Variables JavaScript uses `let`, `const`, and `var` to declare variables.
var was the big player earlier. ECMAScript, var is deprecated.
We'll focus on `let` and `const`.
```javascript // Declare a variable let age = 25; console.log(age);
// Declare a constant const PI = 3.14159; console.log(PI); ```
Exercise: Declare variables for a person's name, age, and whether they are a student.
1.2 Data Types JavaScript has several basic data types: number, string, boolean, undefined, and null.
```javascript let num = 42; // number let name = "Alice"; // string let isStudent = true; // boolean let grade; // undefined let empty = null; // null
console.log(typeof num, typeof name, typeof isStudent, typeof grade, typeof empty); ```
Exercise: Create variables of each data type and use `typeof` to check their types.
Part 2: Flow Control
2.1 Variable Assignment and Comparison
```javascript let x = 5; let y = 10;
console.log(x === y); // false console.log(x !== y); // true console.log(x < y); // true console.log(x >= y); // false ```
Exercise: Create two number variables and compare them using different operators.
2.2 If-Then Branching
```javascript let temperature = 22;
if (temperature > 30) { console.log("It's hot outside!"); } else if (temperature > 20) { console.log("It's warm outside."); } else { console.log("It's cool outside."); } ```
Exercise: Write an if-else statement to categorize a person's age into child, teenager, adult, or senior.
2.3 Loops (Repetition)
For Loop: ```javascript for (let i = 0; i < 5; i++) { console.log(`Iteration ${i}`); } ```
While Loop: ```javascript let count = 0; while (count < 5) { console.log(`Count is ${count}`); count++; } ```
home work:Exercise: Use a for loop to print the first 10 even numbers.
2.4 Functions (Reusable Code Blocks)
```javascript function greet(name) { return `Hello, ${name}!`; }
console.log(greet("Alice")); console.log(greet("Bob"));
/// July 29: we will resume from here.
// And do classes and Objects.
Exercise: Write a function that takes two numbers as parameters and returns their sum.
Part 3: Combining Concepts
Let's create a simple program that uses all these concepts:
```javascript function calculateGrade(scores) { let total = 0; for (let i = 0; i < scores.length; i++) { total += scores[i]; } let average = total / scores.length; if (average >= 90) { return 'A'; } else if (average >= 80) { return 'B'; } else if (average >= 70) { return 'C'; } else if (average >= 60) { return 'D'; } else { return 'F'; } }
let studentScores = [85, 92, 78, 95, 88]; let grade = calculateGrade(studentScores); console.log(`The student's grade is: ${grade}`); ```
Final Exercise: Create a program that: 1. Asks for a user's name (you can hardcode this for now) 2. Has an array of at least 5 quiz scores 3. Calculates the average score 4. Determines if the user passed (average >= 70) or failed 5. Prints a personalized message with the result
This lab covers the basics of variables, data types, flow control (if-then, loops), and functions in JavaScript. It provides a solid foundation for students to build upon as they dive deeper into full-stack web development.

image.png

image.png

A Web Application is a Client - Server Application.

Summary, Review, and Continuation:

The purpose is to construct a Full Stack Web Application.
Pattern : MVC
Model : Database : For us here in land, we will be using Mongo DB, based on a way of storing and retrieving data called JSON : JavaScript Object Notation.
View : Point of Interaction with the User: expressjs
Controller: we write JavaScript Objects to run the application. Business Rules and Algorithms are encoded in JavaScript Objects here.

Here is the Technology Stack we use to make a Nodejs Full Stack Web Application:

→ Download and Install Nodejs → This is a wrapper around Chromium v8 JavaScript Interpeter.
JavaScript in the Web Browser: Browser Object Model BOM:
This let’s you use JavaScript

"Web Wizardry: Crafting Your Digital Dating Destiny"

Table of Contents and Progress Checklist

Phase 1: The Magical Setup and Client-Side Sorcery

1.1 Summoning Node.js (Installation)
1.2 Conjuring an Express.js Project
1.3 Enchanting a Client-Side Calculator
Exercise 1: Expanding Your Magical Calculator

Phase 2: Server-Side Spell Casting

2.1 Brewing a Server-Side Calculator
Exercise 2: Defensive Magic (Error Handling)

Phase 3: The Art of Handlebars Illusion

3.1 Mastering the Handlebars Technique
Exercise 3: The Partial Spell (Creating Reusable Components)

Phase 4: MongoDB - The Database

4.1 Harnessing the Power of MongoDB and Mongoose
Exercise 4: The Transformation Spell (Editing Profiles)

Phase 5: Advanced Skills

5.1 Image Upload
Exercise 5: Implementing Search

Bonus Quests

Implement user authentication
Add real-time chat functionality
Create a matching algorithm

Grimoire of Knowledge (Resources)

Node.js
Express.js
MongoDB
Mongoose Parchment
Handlebars
Multer
This outline provides a structured journey through the "Web Wizardry" lab, allowing students to track their progress and ensure they've completed all the necessary steps in their quest to master web development.

minus

Building a 3-Tier MVC Web Application with Express and MongoDB


Transcription of this lesson:
Loading…

Introduction

Welcome to Assignment 2 of MO1003 Web Programming.

In this assignment, you will build a 3-Tier Model-View-Controller (MVC) web application using Express.js and MongoDB. To make a server side Web Application: We must first install Node.js.
This will also get us: npm : node package manager : npm -i <npm packages> such as
express
body-parser
mongo
handlebars
info

Edged graph representing the key Node.js concepts and how they connect to build a 3-tier web application.

This visualization will help students understand the relationships between different components.

Graph: Node.js Concepts for 3-Tier Web Application
Vertices (Nodes):
Node.js
Express.js
MongoDB
Mongoose
HTML/CSS
Client-side JavaScript
Server-side JavaScript
Handlebars (templating engine)
Body-parser middleware
Multer (file upload)
Model (MVC)
View (MVC)
Controller (MVC)
Edges (Connections):
Node.js -> Express.js (Express runs on Node.js)
Express.js -> Server-side JavaScript (Express apps are written in server-side JS)
Express.js -> Body-parser middleware (used for parsing form data in Express)
Express.js -> Handlebars (Express uses Handlebars for templating)
Express.js -> Multer (Express uses Multer for file uploads)
MongoDB -> Mongoose (Mongoose is an ODM for MongoDB)
Mongoose -> Model (Mongoose defines data models)
HTML/CSS -> View (HTML/CSS make up the View layer)
Client-side JavaScript -> View (Client-side JS enhances the View)
Server-side JavaScript -> Controller (Server-side JS implements controller logic)
Handlebars -> View (Handlebars generates dynamic HTML views)
Model -> MongoDB (Models are stored in MongoDB)
Controller -> Model (Controller interacts with Model for data)
Controller -> View (Controller sends data to View)
View -> Client-side JavaScript (View contains client-side JS)
This graph illustrates how the various components of the 3-tier web application are interconnected. Node.js serves as the foundation, with Express.js building on top of it to create the web server. The MVC pattern is implemented using Mongoose for the Model, Handlebars for the View, and server-side JavaScript for the Controller. MongoDB provides the database backend, while client-side JavaScript enhances the user interface.
By visualizing these connections, students can better understand how each piece fits into the larger picture of building a full-stack web application using Node.js and related technologies.

Step 0: Test that nodejs is available.

Open a command prompt and type: node
image.png
image.png
This workbook is designed for students with no prior experience in Node.js, npm, Express, MongoDB, and JSON data handling.
Hopefully you have a little HTML and CSS.

Learning Outcomes:

By the end of this assignment, you will be able to:
Set up and use Node.js and Express.js
Understand and implement client-side and server-side JavaScript:
Client side JavaScript runs in the BOM
Server-side JS runs in Node.js
Use templating engines for dynamic web pages
Integrate a MongoDB database with an Express application to provide the persistance layer for our MVC Application.
Your final output will be a small scale Amazon.com: a full-stack web application following MVC architecture

What is 3-Tier MVC Architecture?

The 3-Tier MVC (Model-View-Controller) architecture is a software design pattern that separates an application into three interconnected components:
Model: Manages data and business logic
View: Handles layout and display
Controller: Routes commands to the model and view parts
This separation allows for efficient code organization, easier maintenance, and scalability.


The role of the Form:
image.png

Phase 1: Setting Up and Client-Side JavaScript

Objectives:

We will be working in Visual Studio Code.
Install Node.js and set up an Express.js web server
Understand client-side JavaScript in the Browser Object Model (BOM)
Create a simple calculator application that runs client-side only

1.1 Installing Node.js

Visit the official Node.js website:
Download the LTS (Long Term Support) version for your operating system
image.png
Run the installer and follow the prompts to complete the installation
Verify the installation by opening a terminal/command prompt and typing:
node --version
npm --version
You should see version numbers for both Node.js and npm.

1.2 Setting up an Express.js project

Working in VSC: Create a new directory for your project:
mkdir calculator-app
cd calculator-app
image.png

Initialize a new Node.js project:

npm init -y

-> this creates your package.json file, which is the configuration file of your Node.js app

Install Express from NPMjs.com:
npm install express
image.png

Create a file named app.js and add the following code:

Note: This is the controller in Model-View-Controller

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

app.use(express.static('public'));

app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});

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

Create a public directory in the root of your project folder


Creating a client-side calculator

image.png
In the public directory, create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" readonly>
<button class="btn" onclick="appendToDisplay('7')">7</button>
<button class="btn" onclick="appendToDisplay('8')">8</button>
<button class="btn" onclick="appendToDisplay('9')">9</button>
<button class="btn" onclick="appendToDisplay('+')">+</button>
<button class="btn" onclick="appendToDisplay('4')">4</button>
<button class="btn" onclick="appendToDisplay('5')">5</button>
<button class="btn" onclick="appendToDisplay('6')">6</button>
<button class="btn" onclick="appendToDisplay('-')">-</button>
<button class="btn" onclick="appendToDisplay('1')">1</button>
<button class="btn" onclick="appendToDisplay('2')">2</button>
<button class="btn" onclick="appendToDisplay('3')">3</button>
<button class="btn" onclick="appendToDisplay('*')">*</button>
<button class="btn" onclick="appendToDisplay('0')">0</button>
<button class="btn" onclick="appendToDisplay('.')">.</button>
<button class="btn" onclick="calculate()">=</button>
<button class="btn" onclick="appendToDisplay('/')">/</button>
<button class="btn" onclick="clearDisplay()">C</button>
</div>
<script src="script.js"></script>
</body>
</html>

Create a styles.css file in the public directory:

styles.css is being passed to requesting web browser a static asset.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
}

.calculator {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.