Share
Explore

Student Lab Learning Workbook: Building a JavaScript Website Calculator Application with Express.js

In this workbook, you will learn how to build a simple JavaScript web application using **Express.js**, a popular Node.js framework. The application will serve an HTML page containing a calculator form that allows users to input two numbers and perform basic arithmetic operations (addition, subtraction, multiplication, and division). By the end of this workbook, you will have a fully functional Node.js application that can be published using `npm publish`.

Prerequisites
- Basic knowledge of **JavaScript** and **HTML**.
- **Node.js** and **npm** installed on your machine.
- A code editor (e.g., Visual Studio Code).

Step 1: Setting Up the Project

1.1 Initialize a New Node.js Project
1. Open your terminal and create a new directory for your project:
```bash
mkdir express-calculator
cd express-calculator
```
2. Initialize a new Node.js project:
```bash
npm init -y
```
This will create a `package.json` file with default settings.

1.2 Install Express.js
Install **Express.js** as a dependency:
```bash
npm install express

Step 2: Creating the Express.js Web Server

2.1 Create the Server File
1. Create a new file named `server.js` in your project directory.
2. Add the following code to set up a basic Express.js server:

```javascript
// server.js
const express = require('express');
const app = express();
const port = 3000;

// Serve static files (like HTML, CSS, JS)
app.use(express.static('public'));

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

2.2 Create the Public Directory
1. Create a new directory named `public` in your project folder. This directory will hold your static files (HTML, CSS, JS).
2. Inside the `public` directory, create an `index.html` file.
Step 3: Building the Calculator Form

3.1 Create the HTML Form
In the `public/index.html` file, add the following HTML code to create a calculator form:

```html
<!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 id="calculatorForm">
<label for="num1">Number 1:</label>
<input type="number" id="num1" name="num1" required>
<br>
<label for="num2">Number 2:</label>
<input type="number" id="num2" name="num2" required>
<br>
<button type="submit" name="operation" value="add">Add</button>
<button type="submit" name="operation" value="subtract">Subtract</button>
<button type="submit" name="operation" value="multiply">Multiply</button>
<button type="submit" name="operation" value="divide">Divide</button>
</form>
<h2>Result: <span id="result"></span></h2>

<script>
// JavaScript to handle form submission
document.getElementById('calculatorForm').addEventListener('submit', function(event) {
event.preventDefault();
const num1 = parseFloat(document.getElementById('num1').value);
const num2 = parseFloat(document.getElementById('num2').value);
const operation = event.submitter.value;

fetch('/calculate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ num1, num2, operation }),
})
.then(response => response.json())
.then(data => {
document.getElementById('result').textContent = data.result;
});
});
</script>
</body>
</html>
```
3.2 Explanation of the HTML Form
- The form contains two input fields for numbers (`num1` and `num2`).
- Four buttons are provided for the operations: **Add**, **Subtract**, **Multiply**, and **Divide**.
- When the form is submitted, the JavaScript code sends a **POST** request to the `/calculate` endpoint with the numbers and the selected operation.


Step 4: Handling the Calculation on the Server

4.1 Add the Calculation Endpoint
In the `server.js` file, add the following code to handle the `/calculate` endpoint:

```javascript
// server.js
const express = require('express');
const app = express();
const port = 3000;

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

// Serve static files
app.use(express.static('public'));

// POST endpoint for calculations
app.post('/calculate', (req, res) => {
const { num1, num2, operation } = req.body;
let result;

switch (operation) {
case 'add':
result = num1 + num2;
break;
case 'subtract':
result = num1 - num2;
break;
case 'multiply':
result = num1 * num2;
break;
case 'divide':
result = num1 / num2;
break;
default:
result = 'Invalid operation';
}

res.json({ result });
});

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

4.2 Explanation of the Calculation Endpoint
- The `/calculate` endpoint receives a **POST** request with the numbers and the operation.
- A `switch` statement is used to perform the appropriate calculation based on the operation.
- The result is sent back to the client as a JSON response.

Step 5: Testing the Application

5.1 Start the Server
Run the following command to start the Express.js server:
```bash
node server.js
```

5.2 Open the Application in a Browser
Open your browser and navigate to `http://localhost:3000`. You should see the calculator form. Enter two numbers, select an operation, and click the corresponding button to see the result.

Step 6: Preparing for npm Publish

6.1 Update the `package.json` File
To prepare your application for publishing on npm, update the `package.json` file with the following fields:

```json
{
"name": "express-calculator",
"version": "1.0.0",
"description": "A simple calculator web application using Express.js",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"keywords": ["express", "calculator", "nodejs"],
"author": "Your Name",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
}
}
```

6.2 Publish to npm
1. If you don’t have an npm account, create one at [npmjs.com](https://www.npmjs.com/).
2. Log in to your npm account from the terminal:
```bash
npm login
```
3. Publish your package:
```bash
npm publish
```
Conclusion
Congratulations! You have successfully built a simple JavaScript web application using **Express.js** and prepared it for publishing on npm. This workbook covered the basics of setting up an Express.js server, creating an HTML form, handling form submissions, and performing calculations on the server. You can now expand this application by adding more features or improving the user interface.



megaphone
The html forms communicate to the app.js endpoints, and app.js mediates talking to the database

🔍 Understanding How HTML Forms Communicate with MongoDB via app.js

The HTML forms send data to app.js, and app.js acts as a mediator between the frontend and the database (MongoDB).

📌 How the Communication Works

Step-by-Step Flow

Table 1
Step
Action
Technology Used
1. User submits a form
User fills out an HTML form and clicks "Submit"
HTML
2. Form sends an HTTP request
The form sends data via a POST request to app.js
JavaScript, Fetch API
3. Express (app.js) receives request
Express routes in app.js capture the request
Node.js, Express.js
4. Mongoose processes the request
Mongoose interacts with MongoDB to save/update/delete data
Mongoose, MongoDB
5. Response is sent back
Express sends a response (redirect, JSON, or success message)
Express.js
6. JavaScript updates the frontend
Fetch API updates the UI dynamically by retrieving new data
JavaScript, DOM Manipulation
There are no rows in this table

📌 Code Walkthrough: HTML Forms → app.js → MongoDB

Let's analyze the full request-response cycle.

🔹 1. HTML Form (Frontend)

📌 Users fill out a form and click "Add Item".
<form id="addForm">
<input type="text" id="name" name="name" placeholder="Item Name" required>
<input type="number" id="quantity" name="quantity" placeholder="Quantity" required>
<button type="submit">Add Item</button>
</form>
<ul id="shopping-list"></ul>
📌 JavaScript captures form submission and sends data to app.js.
document.getElementById("addForm").addEventListener("submit", async (e) => {
e.preventDefault(); // Prevent page refresh
const name = document.getElementById("name").value;
const quantity = document.getElementById("quantity").value;

await fetch("/add", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `name=${name}&quantity=${quantity}`
});

fetchItems(); // Refresh UI
});

Sends form data to /add endpoint in app.js via POST.Prevents page reload and updates the UI dynamically.

🔹 2. app.js Handles the Request (Backend)

📌 app.js captures the request and stores the data in MongoDB.
const express = require("express");
const mongoose = require("mongoose");
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.