Skip to main content

Command Palette

Search for a command to run...

L12.πŸ“ Node.js – Handling Forms with Express

Published
β€’2 min readβ€’View as Markdown
import express from 'express';

const app = express();

// When I enter a name, it will be displayed in the URL like this:
// http://localhost:1000/?name=sahana&email=
// To handle this kind of form data, we need middleware.
// For this, we use built-in middleware: urlencoded
// This is a built-in middleware in Express used to parse incoming request bodies 
// with URL-encoded data, which is commonly sent through HTML forms.
app.use(express.urlencoded({ extended: true }));

// After hitting the submit button, we need to know where the data goes.
app.get('/', (req, res) => {
    res.render('index.ejs');
});

app.post('/form-submit', (req, res) => {
    console.log(req.body);
    // Example output:
    // { name: 'Sahana', email: 'sahanaa85@gmail.com' }
    // This data will be displayed in the console.
    // This is where form data is saved to the database.

    res.json({
        message: "Your form has been submitted",
        success: true
    });
});

// When the user presses submit, the data should go to the /form-submit route.
// Here we can save the data to a database using the POST method.
// To see what data the user has submitted β†’ it’s inside express body.
// Everything can be accessed through req.body

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>