Skip to content
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
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.