Skip to content
Share
Explore

MADS 4012 Full Stack Web Application Development: Session 4,5: February 1, 2

Session 5 - February 2 Building the full stack application: Connecting Express.js with the MONGO Database
Today’s developments of Mongo DB front-ended by Express.js : here are a number of build it up development versions of the code.
This will introduce the ways in which your Express Code must integrate with your MONGO Code. (Database name, schema name)
Here is the finished Gold Version of the Code:

Warm up Drill
megaphone

Below is a simple warm-up Express.js program in Node.js that presents a calculator application.

The code incorporates ECMAScript 6 best practices, including the use of async/await for making Mongoose calls, async/await statements wrapped in try-catch, and arrow function syntax.

```javascript // Required Dependencies const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose');
// Initialize Express App const app = express();
// Middleware app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine', 'ejs');
// MongoDB Connection mongoose.connect('mongodb://localhost:27017/calculatorDB', { useNewUrlParser: true, useUnifiedTopology: true }); const calculatorSchema = new mongoose.Schema({ num1: Number, num2: Number, result: Number }); const Calculator = mongoose.model('Calculator', calculatorSchema);
// Routes app.get('/', (req, res) => { res.render('index'); });
app.post('/calculate', async (req, res) => { const { num1, num2, operation } = req.body; let result;
try { switch (operation) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: throw new Error('Invalid operation'); }
const newCalculation = new Calculator({ num1: num1, num2: num2, result: result });
await newCalculation.save(); res.render('index', { result: result }); } catch (error) { res.status(500).send('An error occurred during calculation'); } });
// Start Server app.listen(3000, () => { console.log('Server is running on port 3000'); }); ```
In this example, the code uses async/await for making Mongoose calls to the MongoDB database. The await statements are wrapped in a try-catch block to handle errors effectively. Additionally, arrow function syntax is used throughout the code for concise and clear function definitions. This program sets up an Express server with a basic calculator functionality, allowing users to perform addition, subtraction, multiplication, and division operations on input numbers.
megaphone

Understanding EJS (Embedded JavaScript)

Introduction

Welcome, students! Today, we will delve into the world of EJS, also known as Embedded JavaScript. EJS is a popular template engine for Node.js and Express.js, used to generate HTML markup with plain JavaScript.

Part 1: What is EJS?

1.1 Definition

EJS is a simple templating language that lets you generate HTML markup with JavaScript. It allows you to embed JavaScript code directly within your HTML files.

1.2 Features

EJS supports both server-side and client-side template rendering.
It provides a straightforward syntax for embedding dynamic content, including variables, control flow, and template inclusion.
EJS enforces a clear separation between logic and presentation, facilitating code organization and reusability.

1.3 Example:

html<h1>Hello, <%= user.name %>!</h1>
In this example, <%= user.name %> is an EJS tag that injects the value of user.name into the HTML output.

Part 2: Integration with Node.js/Express.js

2.1 Setup

EJS can be easily integrated with Node.js and Express.js using the ejs package, which is commonly used for server-side rendering of templates.

2.2 Example Usage:

const express = require('express'); const app = express();
// Set 'ejs' as the view engine app.set('view engine', 'ejs');
// Render an EJS template
app.get('/', (req, res) => { const data = { user: { name: 'John' } };
res.render('index', { data }); });
In this example, we set EJS as the view engine for Express. When rendering the 'index' template, we pass a data object containing dynamic content to be injected into the template.

Part 3: Use Cases

3.1 Dynamic Content

EJS is ideal for rendering dynamic content, such as user-specific data, database records, or real-time information.

3.2 Reusable Components

It enables the creation of reusable template components, promoting modular design and code reusability.


In conclusion, EJS (Embedded JavaScript) serves as a powerful tool for generating HTML templates with dynamic content using JavaScript. Its seamless integration with Node.js and Express.js makes it a popular choice for server-side rendering in web applications.

By understanding EJS, students gain valuable insights into the world of server-side template rendering and dynamic content generation. This knowledge equips them with a versatile tool for building interactive and data-driven web applications using Node.js and Express.js.An example of what the content of the "index.ejs" file could look like. This file should be placed in a directory called "views" in the root directory of your Express application:

In our express.js program, the views directory is being referenced in the following line of code:

javascriptapp.set('view engine', 'ejs');

In this line, the app.set method is used to set the 'view engine' to 'ejs'. When Express is configured in this way, it automatically knows that the templates are stored in a directory named "views". This is a convention in Express.js where the views directory is assumed to be named "views" unless otherwise specified.

Therefore, when you provide the view engine as 'ejs', Express expects to find the EJS template files in the "views" directory. This is how Express knows where to look for the EJS templates when rendering them for a route.
Additionally, when rendering the EJS templates using res.render() method, Express will look for the specified template file within the "views" directory by default unless a specific path is provided.
So, the line app.set('view engine', 'ejs'); is where the views directory is referenced and configured as the default location for EJS templates in the Express application.
In this "index.ejs" file, we have a simple HTML form for entering two numbers and choosing an arithmetic operation. When the form is submitted, it makes a POST request to the "/calculate" route in the Express app. If there is a result available, it will be displayed below the form.
Make sure to save this code in a file named "index.ejs" and place it in a directory called "views" in the root directory of your Express application.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculator</title> </head> <body> <h1>Simple Calculator</h1> <form action="/calculate" method="post"> <input type="number" name="num1" placeholder="Enter first number" required> <select name="operation"> <option value="+" selected>Addition (+)</option> <option value="-">Subtraction (-)</option> <option value="*">Multiplication (*)</option> <option value="/">Division (/)</option>

</select> <input type="number" name="num2" placeholder="Enter second number" required> <button type="submit">Calculate</button> </form>
<% if (typeof result !== 'undefined') { %> <h2>Result: <%= result %></h2> <% } %> </body> </html>
minus

Here's a line-by-line explanation of what the provided Express.js program does:

```javascript // Required Dependencies const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose');
// Initialize Express App const app = express();
// Middleware app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine','ejs');
// MongoDB Connection mongoose.connect('mongodb://localhost:27017/calculatorDB', { useNewUrlParser: true, useUnifiedTopology: }); ``` 1. Required Dependencies: The program begins by requiring the necessary modules: `express` for creating the server, `body-parser` for handling form data, and `mongoose` for interacting with the MongoDB database. 2. Initialize Express App: It initializes an instance of the Express application. 3. Middleware: The program uses `bodyParser` middleware to parse URL-encoded form data and sets the view engine to 'ejs' for rendering dynamic content using EJS templates. 4. MongoDB Connection: It establishes a connection to the MongoDB database named 'calculatorDB' using `mongoose`, specifying connection options.
```javascript // Define MongoDB Schema and Model const calculatorSchema = new mongoose.Schema({ num1: Number, num2: Number, result: Number }); const Calculator = mongoose.model('Calculator', calculatorSchema); ``` 1. Define MongoDB Schema and Model: It defines a Mongoose schema named `calculatorSchema` with fields for `num1`, `num2`, and `result`, representing the numbers to be operated on and the result of the operation. Then, it creates a Mongoose model named `Calculator` based on the schema.
```javascript // Routes app.get('/', (req, res) => { res.render('index'); }); ``` 1. Index Route: It handles the GET request to the root URL ('/'). When accessed, it renders the 'index' template, which will likely contain the form for calculator input and display of the result.
```javascript app.post('/calculate', async (req, res) => { const { num1, num2, operation } = req.body; let result;
try { // Perform Calculation based on the operation switch (operation) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: throw new Error('Invalid operation'); }
// Save the calculation to the MongoDB database const newCalculation = new Calculator({ num1: num1, num2: num2, result: result });
await newCalculation.save(); // Render the result on the index page res.render('index', { result: result }); } catch (error) { // Handle any errors that occur during the calculation or database operation res.status(500).send('An error occurred during calculation'); } }); ``` 1. Calculate Route: It handles the POST request to the '/calculate' URL. It retrieves the input `num1`, `num2`, and `operation` from the request body and performs the corresponding calculation based on the chosen operation (`+`, `-`, `*`, or `/`). 2. Database Interaction: It creates a new instance of the `Calculator` model with the input numbers and the result, and saves it to the MongoDB database. The `save` method is awaited to ensure the operation completes before rendering the result. 3. Response Handling: Any errors that occur during the calculation or database operation are caught and a 500 Internal Server Error response is sent with an appropriate message.
```javascript // Start Server app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` 1. Start Server: It starts the Express server to listen on port 3000 and logs a message indicating that the server is running.
This program sets up an Express server to handle rendering the calculator interface, performing calculations, and storing the results in a MongoDB database, all following ECMAScript 6 best practices.

Learning Outcomes:
Let’s make an interesting full stack Node.js application to exercise the power of the Node.js Application Development Framework:
Explainer Video:
megaphone

Lecture: Understanding req and res in Express and Post/Get Encoding with Forms

Introduction

In Express.js, handling HTTP requests and responses is fundamental to building web applications. Additionally, understanding how data is exchanged between the client and the server using form submissions is crucial. This lecture will cover the concepts of req and res in Express, as well as the Post/Get encoding with forms.

Part 1: Understanding req and res in Express

1.1 Request (req) Object

When a client makes an HTTP request to the server, Express handles this request with the req object.
The req object contains information about the HTTP request made by the client, such as parameters, query strings, headers, and body content.

1.2 Response (res) Object

Once the server processes the request, it uses the res object to send a response back to the client.
The res object allows us to set response headers, status codes, and send the response data back to the client.

1.3 Example:

javascriptapp.get('/example', (req, res) => { // Accessing query parameters from the request URL const name = req.query.name; // Sending a JSON response back to the client res.status(200).json({ message: `Hello, ${name}!` }); });
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.