Handling HTML forms with Node JS

Introduction

Forms form a core part of building functional web pages. It allows to take user input data, perform actions, and interact with the website. From login pages to surveys and contact forms, they are essential to gather and process user data.

This guide walks you through creating an HTML Form and handling form submissions on a server in the backend, that is built with Node.js and Express.

Build a folder structure as follows:

backend folder contains the file for building the server. The Form folder contains the frontend file index.html, which serves as the client.

Creating the form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Manipulation</title>
    <script src="./index.js" defer></script>
</head>
<body>
    <form action="" id="myform">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">
        <!-- "for" of Label tag and "id" of input tag must be same, to bind them together -->
<br><br>
        <label for="date">Date of Birth:</label>
        <input type="date" name="date" id="date">
        <br><br>
<span>Select your Gender: </span>
<label for="Gender">
<input id="Gender" type="radio" name="Gender" value="Male"> Male
</label>

<label for="Gender">
<input id="Gender" type="radio" name="Gender" value="Female"> Female</label>

<!-- Check Boxes -->
<label for="Gender">
<input id="Gender" type="radio" name="Gender" value="Others"> Others</label><br><br>

    <span>Skills: </span>
    <label for="html">
        <input id="html" type="checkbox" name="skill" value="html"> HTML</label>

    <label for="css"><input id="css" type="checkbox" name="skill" value="css"> CSS</label>
    <label for="js"><input id="js" type="checkbox" name="skill" value="js"> JavaScript</label>

    <br><br>
    <button type="submit" >Submit</button>
    </form>
</body>
</html>

This code will create a very basic HTML form structure. You can always go and add CSS. Not to mention Bootstrap would be another really good choice for designing your forms, as it contains many predefined and predesigned templates.

For a simple overview, the form contains 4 fields, Name, Date, Gender, and Skill.

Name as text, Date as date, Gender as RadioButton, and Skill as Checkbox.

Setting up the Node Server

Before handling form submissions, we need to set up a simple Node.js project and install the required dependencies

Initialize the project

Run the following command to initialize the node project

npm init -y

Install express and cors that is required for building the project.

npm install express cors

Express is the node framework that facilitates the process of creating the server.

Cors - It stands for Cross-Origin resource sharing. It is needed for authorized resource sharing with external third parties. Here we need it to make a successful post request from the client to the server.

Creating the server

Now we will create the server, that will receive the data from the client for further processing.

const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.post('/api/form',  (req,res)=>{
    const data =   req.body
    console.log('Received data:', data)
    res.json({
        message:'Form data received successfully',
        received: data
    })
})
app.listen(port,()=>{
    console.log("Server is running")
})

This will create a server, that exposes one endpoint- /api/form, that we will use to handle post requests from the client. This basically will be the point where we will send the data collected from the frontend to the backend to perform further processing with the same.

For a quick overview, we create an express server and create a route that handles the post request from the client. We use the CORS to ensure cross-origin connections.

Start the server by running the command node index.js

Getting the data from the client

You must have noticed that the HTML code contains multiple input fields. These are the places where the user will provide their data. We need a certain way by which we can collect those inputs into a certain data type such that it can easily be sent to the server.

Create a file named script.js

const form = document.getElementById('myform')
form.addEventListener('submit',async(e)=>{
        // this prevents the form from reloading each time we submit it.
       e.preventDefault();
       const data = {};
        //Selecting all the input tags
       const inputs = document.querySelectorAll("input");

       inputs.forEach((inp) => { 
        if (inp.type === "radio") {
          if (inp.checked) {
            data[inp.name] = inp.value;
          }
        } 
        else if (inp.type === "checkbox") {
      if (inp.checked) {
      if (!data[inp.name]) {
        data[inp.name] = [];
      }
      data[inp.name].push(inp.value);
    }
  }
        else {
          data[inp.name] = inp.value;
        }
       });
       console.log(data)
       // posting to server
        const myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");
        // fetch api - the way to 'post' the data from the 
        const response = await fetch("http://localhost:3000/api/form", {
          method: "POST",
          body: JSON.stringify(data),
          headers: myHeaders,
        });
        console.log(response);
})

This above code converts all the inputs into an object, which is sent to the server by creating a post request at the server endpoint ` http://localhost:3000/api/form`.

Conclusion

Handling HTML forms with a Node.js server is straightforward with Express. You’ve learned to set up a Node.js project, create a simple HTML form, handle form submissions, validate data, and respond to users. This is a foundational skill for building any interactive website or web application. From here, you can expand your application by storing form data in a database or integrating other tools to create a more dynamic user experience.

Feel free to experiment further, and happy coding!

Did you find this article valuable?

Support Aritra's Blog by becoming a sponsor. Any amount is appreciated!