import express from 'express';
const app = express();
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.render('index.ejs');
});
app.post('/form-submit', (req, res) => {
console.log(req.body);
res.json({
message: "Your form has been submitted",
success: true
});
});
const port = 1000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
π HTML β Form Handling Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Handling</title>
<style>
body {
background-color: black;
color: aquamarine;
}
</style>
</head>
<body>
<h1>Form Handling</h1>
<!-- action: when I press the submit button, where should the data go? -->
<!-- It will go to the specified route -->
<!-- method: GET, POST, etc. -->
<!-- If the method is POST, the values passed from the form will not appear in the URL -->
<!-- After submitting the form, it will redirect to the specified route -->
<!-- The server-side code for saving the form data should be written in that route -->
<form action="/form-submit" method="post">
Name:
<input type="text" name="NAME" placeholder="Enter your name">
<br>
<!-- Example output:
{ NAME: 'Sahana', email: 'sahanaa85@gmail.com' }
-->
<!-- Here, the 'name' attribute in input fields refers to the keys in req.body -->
Email:
<input type="text" name="email" placeholder="Enter your email">
<br>
<input type="submit" value="Submit">
<br>
</form>
</body>
</html>