Share
Explore

Lab Notebook 1: Building the Level 1 Full Stack Nodejs App

Student Lab Lecture Guide

Introduction

This guide will take you through five progressive exercises to set up an Express.js web server, host static files, use Handlebars as a template engine, create a form, and process form data to log into a text file.

Prerequisites

Basic knowledge of JavaScript
Node.js and npm installed (download from
)

Exercise 1: Setup Express.js Web Server

Objectives:

Initialize a Node.js project
Install Express.js
Create an Express.js web server

Steps:

Open your terminal and navigate to your project directory.
Run npm init -y to initialize a new Node.js project.
Run npm install express to install Express.js.
Create a file named app.js and insert the following code:
javascriptCopy code
const express = require('express');
const app = express();
const PORT = 3000;

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

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

Run node app.js. Access http://localhost:3000 to see “Hello World!”.

Exercise 2: Host Static Files, Image, and HTML File


image.png
image.png

Objectives:

Serve HTML and image files as static files using Express.js.

Steps:

Create a public folder in your project directory. mkdir public
Place an HTML file (index.html) and an image file (image.jpg) inside the public folder.
megaphone

<html>

<head>
<title> Peter's Great Page</title>
</head>
<body>
<h1> Welcome to Peter's Great Page</h1>
</body>
</html>
Update app.js:

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

Restart the server and access http://localhost:3000/index.html and http://localhost:3000/image.jpg.

Exercise 3: Use Node Template Language Handlebars

Objectives:

Install and set up Handlebars
Render a template with Handlebars

Steps:

Install Handlebars: npm install express-handlebars.
Update app.js:
const exphbs = require('express-handlebars');

app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

Creating a Views Folder and main.handlebars File

Objectives:

Set up a views directory to store Handlebars templates.
Create a main layout file for Handlebars.

Steps:

In your project directory, create a new folder and name it views.
Inside the views folder, create a file named main.handlebars.
Open main.handlebars in your text editor and write a basic HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Handlebars Example</title>
</head>
<body>
{{{body}}}
</body>
</html>

In this file, {{{body}}} is a placeholder that Handlebars will use to insert the content of the view that is being rendered.

Creating home.handlebars File

Objectives:

Create a view file to be rendered inside the main layout.

Steps:

Inside the views folder, create another file named home.handlebars.
Open home.handlebars in your text editor and write some content that you want to be rendered:
htmlCopy code
<h1>Welcome to Handlebars!</h1>
<p>This is a basic example of a Handlebars view.</p>

This content will replace the {{{body}}} placeholder in main.handlebars when the home view is rendered.

Updating the Root Route in app.js

Objectives:

Configure the Express app to use Handlebars.
Update the root route to render the home view with the main layout.

Steps:

Open the app.js file in your text editor.
Ensure the following code is present to configure the Express app to use Handlebars as its view engine:
javascriptCopy code
const exphbs = require('express-handlebars');

app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');

Here, defaultLayout: 'main' tells Express to use main.handlebars as the default layout for the views.
Update the root route (/) to render the home view:
javascriptCopy code
app.get('/', (req, res) => {
res.render('home');
});

The res.render('home'); line tells Express to render the home view (i.e., home.handlebars) using the main layout (i.e., main.handlebars). The content of home.handlebars will replace the {{{body}}} placeholder in main.handlebars.
Save the app.js file and restart your server by running node app.js in the terminal.
Now, when you navigate to http://localhost:3000, you should see the content of home.handlebars rendered inside the HTML structure defined in main.handlebars.

Exercise 4: Set Up a Form with Fields to Gather User Data

Objectives:

Create an HTML form within a Handlebars template to collect user data (username and email).

Steps:

1. Update the home.handlebars File:

Open the home.handlebars file located inside the views directory.
Erase any existing content and insert a form with POST method and fields for username and email. The action attribute should be set to /submit which will be the route handling the form submission.
Below is the content to be placed inside the home.handlebars file:

<h1>User Data Form</h1>
<form action="/submit" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<button type="submit">Submit</button>
</form>

In this file:
The <form> tag’s action attribute is set to /submit, meaning the form data will be sent to the /submit URL when the form is submitted.
The method is set to post, which is the HTTP method used to send data to the server.
Two <input> fields collect the username and email, with required attributes ensuring these fields are not left empty.
A <button> submits the form.

2. Handling Form Submission:

Open the app.js file.
Below the existing code, add a new POST route to handle form submissions at the /submit path.
Add the following code to your app.js file:
javascriptCopy code
app.post('/submit', (req, res) => {
const username = req.body.username;
const email = req.body.email;
// Process the username and email here
res.send(`Received the data: ${username}, ${email}`);
});
In this block:
app.post('/submit', (req, res) => {...} creates a new route that listens for POST requests at the /submit URL.
const username = req.body.username; and const email = req.body.email; extract the username and email values from the form data.
res.send(...); sends a response back to the client, confirming receipt of the data.
Note: For the server to correctly parse the incoming request body, ensure that the app.use(express.urlencoded({ extended: true })); middleware is set in your app.js.
Here is how the middleware should be included in app.js:

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

app.use(express.urlencoded({ extended: true }));

Save the changes to app.js and restart the server with node app.js.
Now, when you navigate to http://localhost:3000, you will see a form. Upon submission, the server will receive the form data and respond with a confirmation message displaying the received username and email.

Exercise 5: Process Form Data and Log to Text File

Objectives:

Process the form data on the server-side.
Log the received form data to a text file (data.txt).

Steps:

1. Update the /submit POST Route in app.js:

In the app.js file, create a /submit POST route.
Utilize express.urlencoded({ extended: true }) middleware to parse the form data.
Inside the /submit route, use the fs.appendFile function to write the form data to a data.txt file.
Here's the complete and updated app.js file:
javascriptCopy code
// app.js
const express = require('express');
const fs = require('fs');
const exphbs = require('express-handlebars');
const app = express();
const PORT = 3000;

// Middleware to serve static files from the 'public' directory
app.use(express.static('public'));

// Middleware to parse the incoming request body
app.use(express.urlencoded({ extended: true }));

// Set up Handlebars as the view engine
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Root route to render the home view
app.get('/', (req, res) => {
res.render('home');
});

// POST route to handle form submissions
app.post('/submit', (req, res) => {
// Construct the output string
const output = `Username: ${req.body.username}, Email: ${req.body.email}\n`;

// Write the output to 'data.txt' file
fs.appendFile('data.txt', output, err => {
// If an error occurs, throw an error
if (err) throw err;

// Send a response back to the client
res.send('Data written to file');
});
});

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

2. Ensure the home.handlebars File Contains the Correct Form:

Your home.handlebars should have the following form structure:
<!-- home.handlebars -->
<h1>User Data Form</h1>
<form action="/submit" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Submit">
</form>

Now, when the form is submitted, the server will process the form data and append it to a data.txt file in the project directory. The user will receive a response stating "Data written to file" confirming the successful operation.

Testing:

Run your server with the command node app.js.
Navigate to http://localhost:3000 in a web browser.
Fill out the form with a username and email and submit it.
Check the data.txt file in your project directory to see the appended 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.