Lessons 242 & 243 – Complete 2020 Web Development Bootcamp

Lesson 242 – Responding to Requests with HTML files

In Lesson 236, we learned how to send a response from the server when a request is made by the website user. This is code we used in that lesson –

app.get("/", function(req, res){
   response.send("<h1>Hello World!</h1>");
});

In the above example, we used the respond.send() method to send an individual piece of html as a response. However, if we want to send a whole html file as the response, we can use the respond.sendFile() method. For example –

app.get("/", function(req, res) {
	res.sendFile("index.html");
});

When actually deploying your website “in the wild”. You may not know the exact location on the server of your index.html file. In that case, you should use the following code –

app.get("/", function(req, res) {
	res.sendFile(__dirname + "/index.html");
});

The (__dirname + “/index.html”) will locate the index.html file wherever it is residing on the server.

Lesson 243 – Parsing POST Requests Body Parser

In order to use the numbers input in the html form by a user, we need to be able to use npm body-parser. You can install body-parser in the terminal by using this code –

npm install body-parser

Once body parser is installed, you then create a constant variable for bodyParser like this –

const bodyParser = require("body-parser");

You then use app.use to parse the input information.

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

You then use the app.post() method to collect the two posted numbers, add them together and send the result back to the web browser. This is the code –

app.post("/", function(req, res) {

	var num1 = Number(req.body.n1);
	var num2 = Number(req.body.n2);

	var result = num1 + num2;
	
	res.send("The result of the calculation is " + result);
});

The entire html code for the calculator web app is –

<!DOCTYPE html>
<html>
<head>
	<title>Calculator</title>
</head>

<body>

	<h1>Calculator</h1>

	<form action="/" method="post">
		
		<input type="text" name="n1" placeholder="First Number">
		<input type="text" name="n2" placeholder="Second Number">
		<button type="submit" name="submit">Calculate</button>

	</form>

</body>
</html>

The entire express.js code for the calculator web app is –

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

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

app.get("/", function(req, res) {
	res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {

	var num1 = Number(req.body.n1);
	var num2 = Number(req.body.n2);

	var result = num1 + num2;
	
	res.send("The result of the calculation is " + result);
});

app.listen(3000, function() {
	console.log("Server started on port 3000.")
});