Share
Explore

Building the Express.js Web Server with ROUTES

Lab Submission Instructions:

This lab is the first step in delivering your Project

Background reading on understanding the differences between post and get endpoints:


Lab Learning Outcomes:
Be able to articulate and describe the differences between POST and GET routes as communications pipes from Forms to Server Route END POINTS.
Be able to use POSTMan to visualize and experiment with activating Post and GET Route EndPoints on the Server.
Be able to use Docker and DOCKERHUB to submit your Assignment.

megaphone

Lab Activity A Learning Outcomes:

Server-Side Application Development: Learn how to use ROUTES to connect the front end web page to the backend Controller.
Using URL route parameters to send data to a server endpoint (req.params)
Sending data to a server using a <form> and req.body parameter
Overview of POST requests
Working with HTML forms:
<form> HTML script tag
ACTION attribute is a pointer to the server side program which will receive the form fields as inputs
METHOD attribute can be Post or Get and controls the route communication between the client and server.
Reading data from common form elements (textbox, radio button, <select> drop down) on the server

megaphone

Session 02: Server-Side Application Development

Objectives:

Understand how to use URL route parameters to send data to a server endpoint.
Learn to send data to a server using HTML forms and handle it on the server with Express.js.
Gain a thorough understanding of POST requests and how to handle different form elements on the server.
Develop practical skills in creating routes and handling requests in an Express.js application.

Topics and Tasks:

Review of Session 01
Quick recap of setting up a Node.js project and Express.js server.
Review the importance of routes and endpoints.
Using URL Route Parameters
Explain req.params and how to define dynamic routes in Express.js.
Example: Creating a route to capture a username from the URL.
app.get('/user/:username', (req, res) => {
const username = req.params.username;
res.send(`Hello, ${username}!`);
});

Activity: Create routes with multiple parameters (e.g., /user/:username/age/:age).
HTML Forms and Data Submission (30 minutes)
Form Structure: Explain the <form> element, action, and method attributes.
Method Attribute: Explain the difference between GET and POST methods.
GET: Used for retrieving data.
POST: Used for sending data securely.
Example Form:
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<button type="submit">Submit</button>
</form>

Form Handling in Express:
app.post('/submit', (req, res) => {
const name = req.body.name;
res.send(`Name received: ${name}`);
});

Handling Different Form Elements
Textbox: <input type="text">
Radio Buttons: <input type="radio">
Checkboxes: <input type="checkbox">
Select Dropdown: <select>
Textarea: <textarea>
Example Form:
html
Copy code
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>

<label>Hobbies:</label>
<input type="checkbox" id="reading" name="hobbies" value="Reading">
<label for="reading">Reading</label>
<input type="checkbox" id="traveling" name="hobbies" value="Traveling">
<label for="traveling">Traveling</label>
<input type="checkbox" id="gaming" name="hobbies" value="Gaming">
<label for="gaming">Gaming</label><br><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select><br><br>

<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="4" cols="50"></textarea><br><br>

<button type="submit">Submit</button>
</form>

Handling Form Data in Express:
javascript
Copy code
app.post('/submit', (req, res) => {
const { name, gender, hobbies, country, message } = req.body;
res.send(`Form data received:
Name - ${name},
Gender - ${gender},
Hobbies - ${hobbies},
Country - ${country},
Message - ${message}`);
});

Practical Exercises (30 minutes)
Exercise 1: Create an HTML form with various input types and handle form submission on the server.
Exercise 2: Implement a GET request that captures URL parameters and displays them.
Exercise 3: Create validation for the form inputs on the server-side and return error messages if validation fails.
Q&A and Troubleshooting (15 minutes)
Address any questions or issues students encountered during exercises.
Provide additional explanations and examples as needed.

Additional Topics (Optional if time permits)

Introduction to Query Parameters: How to use req.query to handle query strings in GET requests.
Middleware Functions: How to use middleware to handle common tasks like parsing request bodies and logging.
Session Management: Basic concepts of maintaining user sessions and state in an Express.js application.

Resources:

Summary:

This session will build a strong foundation in handling HTTP POST and GET requests, working with form data, and understanding the importance of routes in an Express.js application. Students will gain hands-on experience through practical examples and exercises, preparing them for more advanced topics in server-side development.

The background of node (the server-side wrapper for JavaScript), NPMjs.com, and NPM Application Development.
megaphone

Node.js: A C++ Wrapper around the Chromium JavaScript Interpreter Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to execute JavaScript code outside of a web browser. It is built on the V8 JavaScript engine, which is developed by Google and used in the Chrome browser. Node.js provides a runtime environment for executing JavaScript code on the server-side, enabling developers to build scalable and high-performance applications. At its core, Node.js is a C++ wrapper around the V8 JavaScript engine. The V8 engine is written in C++ and is responsible for executing JavaScript code efficiently. It compiles JavaScript code into machine code, rather than interpreting it as bytecode, which results in faster execution. Node.js leverages the capabilities of the V8 engine to provide a powerful and efficient runtime environment for JavaScript. The V8 engine itself is designed to be embedded into C++ applications, and Node.js takes advantage of this by providing a C++ wrapper around the V8 engine. This allows developers to interact with the V8 engine and execute JavaScript code from their C++ applications. Node.js provides a set of C++ APIs that enable developers to work with JavaScript objects, handle memory allocation, and interact with the event loop. The C++ wrapper provided by Node.js allows developers to extend the functionality of JavaScript by writing native C++ modules. These modules can be used to perform computationally intensive tasks, access system resources, interact with databases, and more. By combining the power of JavaScript with the flexibility and performance of C++, developers can build robust and efficient applications using Node.js. ​The Browser Object Model (BOM) and the Console Object Model (COM) In the context of JavaScript, the Browser Object Model (BOM) refers to the set of APIs provided by web browsers that allow JavaScript code to interact with the browser window, document, and other browser-specific features. The BOM provides methods and properties to manipulate the browser's history, handle user input, modify the DOM, and perform other browser-related tasks. On the other hand, the Console Object Model (COM) refers to the set of APIs provided by Node.js for interacting with the command-line environment. The COM allows JavaScript code running in a server command-line process to access system resources, read and write files, handle network requests, and perform other server-side tasks. While the BOM and COM serve similar purposes of providing APIs for JavaScript code to interact with the environment, they are specific to their respective contexts. The BOM is available in web browsers, while the COM is available in the Node.js runtime environment. ​Visual Studio Code and the Electron Package Visual Studio Code, a popular code editor developed by Microsoft, is an example of an application that was built using the Electron package from npm. Electron is a framework that allows developers to build cross-platform desktop applications using web technologies such as JavaScript, HTML, and CSS. Electron leverages the power of the Chromium browser, which includes the V8 JavaScript engine, to provide a runtime environment for running web applications as desktop applications. It combines the capabilities of Node.js and Chromium to enable developers to build desktop applications using familiar web technologies. The Electron package, available on npm, provides the necessary tools and APIs for building Electron applications. It allows developers to create application windows, handle user interactions, access system resources, and package the application for distribution on different operating systems. By utilizing the Electron package, the Visual Studio Code team was able to leverage their web development skills and build a powerful, cross-platform code editor. The Electron framework, with its integration of Node.js and the Chromium JavaScript interpreter, provides the necessary foundation for running web applications as desktop applications. In conclusion, Node.js is a C++ wrapper around the Chromium JavaScript interpreter, allowing developers to execute JavaScript code on the server-side.

The Browser Object Model (BOM) provides APIs for JavaScript code to interact with web browsers.

The Console Object Model (COM) provides APIs for JavaScript code to interact with the command-line environment in Node.js.

Visual Studio Code is an example of an application built using the Electron package, which combines Node.js and Chromium to enable the development of cross-platform desktop applications.


The npm Registry, hosted on npmjs.com, is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and other needs of the JavaScript community.
We will be getting our Node packages such as express.js from NPMJS.com.
You will use npm install at the command line to install these packages into your node_modules local repository.



Handin Activities for your Lab Work Submission:

info

Lab exercises to learn how to set up various formats of NPM Web Applications

Note: In Visual Studio Code, the Project is the Directory.
Start by making a new directory and then running npm init to create package.json

image.png
megaphone

Basic Terminal Shell Commands for Working with Node.js and npm

Welcome to today's lecture on the basic terminal shell commands necessary for working with Node.js and npm. This session will cover the fundamental commands you need to create and manage Node.js projects efficiently.
#### 1. **Navigating the File System**
Understanding how to navigate the file system is crucial when working with Node.js projects. Here are some basic commands:
- **`mkdir`**: Creates a new directory. ```bash mkdir projectdirectory ```
- **`cd`**: Changes the current directory. ```bash cd projectdirectory ```
- **`dir` (Windows) / `ls` (Unix/Linux/MacOS)**: Lists the contents of a directory. ```bash dir ```
#### 2. **Setting Up a Node.js Project**
Once you have navigated to your project directory, the next step is to set up your Node.js project.
- **`npm init`**: Initializes a new Node.js project and creates a `package.json` file. ```bash npm init ```
During the initialization process, you will be prompted to provide information about your project, such as the name, version, description, entry point, test command, git repository, keywords, author, and license. You can press `Enter` to accept the default values or type your own.
#### 3. **Installing npm Packages**
To add functionality to your Node.js project, you'll need to install npm packages.
- **`npm install <package-name>`**: Installs a package and adds it to your `package.json` file. ```bash npm install express ```
- **`npm install`**: Installs all dependencies listed in the `package.json` file. ```bash npm install ```
#### 4. **Running Your Node.js Application**
To run your Node.js application, you typically use the `node` command followed by the entry point of your application.
- **`node <file-name>`**: Runs a Node.js application. ```bash node server.js ```
If you've specified a different entry point in your `package.json` file, use that file name instead of `server.js`.
#### 5. **Managing npm Packages**
As you work on your project, you might need to update or uninstall packages.
- **`npm update`**: Updates all packages to their latest version based on the version ranges specified in `package.json`. ```bash npm update ```
- **`npm uninstall <package-name>`**: Uninstalls a package and removes it from `package.json`. ```bash npm uninstall express ```
#### 6. **Viewing npm Package Information**
Sometimes, you need to view detailed information about installed packages or those you intend to install.
- **`npm list`**: Lists installed packages in the current project. ```bash npm list ```
- **`npm info <package-name>`**: Shows detailed information about a package. ```bash npm info express ```
#### 7. **Working with Package Scripts**
You can define custom scripts in your `package.json` file to automate tasks. These scripts can be run using the `npm run` command.
- **Adding a Script**: In your `package.json`, you can define scripts under the "scripts" section. ```json "scripts": { "start": "node server.js", "test": "echo \"Error: no test specified\" && exit 1" } ```
- **Running a Script**: Use the `npm run` command followed by the script name. ```bash npm run start ```
#### 8. **Commonly Used npm Commands**
Here are some additional npm commands that are frequently used:
- **`npm init -y`**: Initializes a new project with default values. ```bash npm init -y ```
- **`npm cache clean --force`**: Clears the npm cache. ```bash npm cache clean --force ```
- **`npm outdated`**: Checks for outdated packages. ```bash npm outdated ```
- **`npm prune`**: Removes extraneous packages. ```bash npm prune ```

Summary

Understanding these basic terminal shell commands is essential for working effectively with Node.js and npm. Here’s a quick recap:
- Navigate and manage directories (`mkdir`, `cd`, `dir`/`ls`). - Initialize and manage Node.js projects (`npm init`, `npm install`). - Run applications (`node <file-name>`). - Manage npm packages (`npm update`, `npm uninstall`). - View package information (`npm list`, `npm info`). - Work with package scripts (`npm run <script>`).
By mastering these commands, you'll be well-equipped to handle the setup, development, and management of your Node.js projects.

First of 5 Activity Evolutions for Lab 1 Hand In:

Setting up routes in the Express.js webserver:


Prerequisites:
Setting up and operating an Express JS Web Server.
Step 1: Make a VSC Project.

In this lab, you'll learn how to set up an Express.js server, handle GET and POST requests, and send data to the server using URL route parameters and HTML forms.

We will also learn how to use Postman to test your endpoints.

Prerequisites

Node.js and npm installed on your computer.
Basic knowledge of JavaScript and HTML.
Text editor or IDE (e.g., VS Code).

Setup

Step 1: Initialize a New Node.js Project

Create a new directory for your project and navigate into it:
mkdir express-lab
cd express-lab
Initialize a new Node.js project: To initialize your project with a Package.json file.
npm init -y

Step 2: Install Express.js

Install the Express.js package:
npm install express

Step 3: Set Up the Express.js Server

Create a file named server.js in your project directory.
Open server.js in your text editor and add the following code to set up a basic Express.js server:
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON bodies

app.get('/', (req, res) => {
res.send('Hello, World!');
});

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

Run your server:
nodemon server.js
Open your browser and go to http://localhost:3000. You should see "Hello, World!".
DONE

megaphone

Now amp up the code so that it reports on the number of hits to each route output to a table on the html page

To display the number of hits to each route in a table on the HTML page, we'll need to modify our server to send an HTML response that includes a table. We'll generate this HTML dynamically based on the hit counters.

Here's the updated code:

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

// Middleware to parse JSON bodies (not needed for current routes)
app.use(express.json());

// Hit counters
const hitCounters = {
'/': 0,
'/test1': 0
};

// Helper function to generate HTML
function generateHtml() {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hit Counter</title>
<style>
table {
width: 50%;
margin: 20px auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid #ddd;
text-align: center;
}
th {
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Hit Counter</h1>
<table>
<tr>
<th>Route</th>
<th>Hits</th>
</tr>
<tr>
<td>/</td>
<td>${hitCounters['/']}</td>
</tr>
<tr>
<td>/test1</td>
<td>${hitCounters['/test1']}</td>
</tr>
</table>
</body>
</html>
`;
}

// Root route
app.get('/', (req, res) => {
hitCounters['/']++;
console.log(`Activity on server: / route accessed ${hitCounters['/']} times`);
res.send(generateHtml());
});

// Test1 route
app.get('/test1', (req, res) => {
hitCounters['/test1']++;
console.log(`Activity on server: /test1 route accessed ${hitCounters['/test1']} times`);
res.send(generateHtml());
});

// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Explanation:

HTML Generation: We added a generateHtml function to dynamically generate the HTML for the response, including a table that shows the number of hits for each route.
Route Handling: Both the root route (/) and the /test1 route call the generateHtml function to generate the HTML response, which includes the updated hit counters.

Testing the Server:

Open your browser and navigate to http://localhost:3000. You should see an HTML page with a table showing the hit counters. The console should log Activity on server: / route accessed 1 times.
Navigate to http://localhost:3000/test1. You should see the same HTML page with the updated hit counters. The console should log Activity on server: /test1 route accessed 1 times.
Refresh the routes in the browser to see the hit counters increment.
This setup allows your Express.js server to dynamically generate an HTML page displaying the number of hits to each route in a table, providing a clear and user-friendly way to monitor route activity.

Handling GET and POST Requests

Step 4: Handle GET Requests

Add a new route to handle GET requests:
app.get('/user/:name', (req, res) => {
const name = req.params.name;
res.send(`Hello, ${name}!`);
});
Restart your server and go to http://localhost:3000/user/YourName. You should see "Hello, YourName!".
image.png
megaphone

Explaining the difference between using URL-encoded parameters with a GET endpoint and using a form to send data to a POST endpoint:

It's essential to understand how HTTP methods work and the conventions associated with them.

### GET Request with URL-Encoded Parameters
1. **Nature of GET Requests**: - GET requests are designed to retrieve data from the server. They are idempotent, meaning multiple identical GET requests should have the same effect as a single request. 2. **URL Structure**: - GET requests can include parameters directly in the URL, which are appended after the question mark (?) as key-value pairs (e.g., `http://localhost:3000/user/YourName`). These parameters are known as URL-encoded parameters. 3. **Visibility and Limitations**: - Because the parameters are part of the URL, they are visible in the browser's address bar and are limited by the URL length restriction of the web browser (usually around 2048 characters).
4. Example in Code: ```javascript app.get('/user/:name', (req, res) => { const name = req.params.name; res.send(`Hello, ${name}!`); }); ``` - In this example, the `:name` part of the URL is a route parameter that can be accessed via `req.params.name` in the server code.

POST Request with Form Data

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.