Learning Express.js. I have the following simple HTML form:
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Calculator</title> </head> <body> <h1>Calculator</h1> <form action="/" method="post"> <input type="text" name="num1" placeholder = "First Number" value=""> <br> <input type="text" name="num2" placeholder = "Second Number" value=""> <br> <button type="submit" name="submit">Calculate</button> </form> </body> </html>
The user is supposed to input two numbers, and their sum is returned to them. The simple Express server is here. body-parser
is included in node_modules
and use
d by the Express app
in order to manipulate the req
object and extract the form data.
const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({extended:true})); app.listen(3000, () => { console.log("Server spun on port 3000.") }); app.get("/", (req, res) => { console.log("Serving a GET request at root route."); res.sendFile(absoluteDirPath() + "index.html"); }); app.post("/", (req, res) => { console.log("Serving a POST request at root route."); let num1 = Number(req.body.num1); let num2 = Number(req.body.num2); if(isNaN(num1) || isNaN(num2)) { res.send("<p>Need numerical values.</p>"); } else { res.send("<h3>Result: " + (num1 + num2) + "</h3>"); } // How can I re-direct the user here? }); function absoluteDirPath() { const path = require('path'); return __dirname + path.sep; }
I am interested in redirecting the user to index.html
in the POST
middleware so that they can use the calculator again without refreshing the URL, whether they used it successfully or not. Since this is in the backend, I don't have access to the window
object and I can't play around with it directly. Not sure how this could be done. Any ideas?
没有评论:
发表评论