Server-Side Scripting/Requests/Node.js (Express)

From Wikiversity
Jump to navigation Jump to search

app.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.
//
//  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/

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

const GET_FORM = `
<form method="GET">
<label for="fahrenheit">Enter Fahrenheit temperature:</label>
<input type="text" id="fahrenheit" name="fahrenheit">
<input type="submit" value="Submit">
</form>
`

const EMTPY_PARAGRAPH = `
<p>&nbsp;</p>
`

const POST_FORM = `
<form method="POST">
<label for="celsius">Enter Celsius temperature:</label>
<input type="text" id="celsius" name="celsius">
<input type="submit" value="Submit">
</form>
`

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

app.get('/', (request, response) => {
    let result = GET_FORM;

    if (request.query.fahrenheit) {
        let fahrenheit = request.query.fahrenheit;
        let celsius = (fahrenheit - 32) * 5 / 9;
        result += "<p>" + fahrenheit + "° Fahrenheit is " +
            celsius + "° Celsius</p>";
    }
    else {
        result += EMTPY_PARAGRAPH;
    }

    result += POST_FORM + EMTPY_PARAGRAPH;

    response.send(result);
});

app.post('/', (request, response) => {
    let result = GET_FORM + EMTPY_PARAGRAPH + POST_FORM;

    if (request.body.celsius) {
        let celsius = request.body.celsius;
        let fahrenheit = celsius * 9 / 5 + 32;
        result += "<p>" + celsius + "° Celsius is " +
            fahrenheit + "° Fahrenheit</p>"
    }
    else {
        result += EMTPY_PARAGRAPH;
    }

    response.send(result);
});

app.listen(3000, () => console.log('server started'));

Try It[edit | edit source]

Copy and paste the code above into the following free online development environment or use your own Node.js (Express) compiler / interpreter / IDE.