Server-Side Scripting/Requests/Node.js (Express)
Appearance
routes/lesson3.js
[edit | edit source]// Converts a Fahrenheit temperature to Celsius using a GET request and
// converts a Celsius temperature to Fahrenheit using a POST request.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/JavaScript
// https://stackabuse.com/get-query-strings-and-parameters-in-express-js/
// https://flaviocopes.com/express-forms/
// https://expressjs.com/en/guide/routing.html
const express = require('express')
const fs = require("fs");
const handlebars = require('handlebars');
const router = express.Router()
router.get("/", function (request, response) {
let result = "";
if (request.query.fahrenheit) {
let fahrenheit = request.query.fahrenheit;
let celsius = (fahrenheit - 32) * 5 / 9;
result = fahrenheit + "° Fahrenheit is " +
celsius + "° Celsius";
}
let source = fs.readFileSync("./templates/lesson3.html");
let template = handlebars.compile(source.toString());
let data = {
fahrenheit: result,
celsius: ""
}
result = template(data);
response.send(result);
});
router.post("/", function (request, response) {
let result = "";
if (request.body.celsius) {
let celsius = request.body.celsius;
let fahrenheit = celsius * 9 / 5 + 32;
result = celsius + "° Celsius is " +
fahrenheit + "° Fahrenheit";
}
let source = fs.readFileSync("./templates/lesson3.html");
let template = handlebars.compile(source.toString());
let data = {
fahrenheit: "",
celsius: result
}
result = template(data);
response.send(result);
});
module.exports = router;
templates/lesson3.html
[edit | edit source]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lesson 3</title>
<link rel="stylesheet" href="styles.css">
<style>
p {
min-height: 1em;
}
</style>
</head>
<body>
<form method="GET">
<p>
<label for="fahrenheit">Enter Fahrenheit temperature:</label>
<input type="text" id="fahrenheit" name="fahrenheit">
<input type="submit" value="Submit">
</p>
<p>
<output>{{fahrenheit}}</output>
</p>
</form>
<form method="POST">
<p>
<label for="celsius">Enter Celsius temperature:</label>
<input type="text" id="celsius" name="celsius">
<input type="submit" value="Submit">
</p>
<p>
<output>{{celsius}}</output>
</p>
</form>
</body>
</html>
Try It
[edit | edit source]See Server-Side Scripting/Routes and Templates/Node.js (Express) to create a test environment.