Handling form submissions is a critical task in web development. Express JS simplifies this process with its efficient and flexible framework. This article explores handling form submissions in Express JS in detail. We will cover topics such as creating forms, GET and POST methods.
Following this article on handling form submission Express JS, you can build robust and secure form submission functionality in Express JS applications.
Express JS
Express JS is a fast, self-contained, minimal web application framework for Node JS.
It offers an easy and flexible approach to building web applications and APIs.
Express JS provides many HTTP utility methods and middleware for handling requests and responses.
We can use it to define routes, handle HTTP methods (GET, POST, PUT, DELETE, etc.), and manage middleware functions.
Express JS provides a modular structure that allows us to extend its functionality using third-party middleware and templating engines.
Form Handling
Express JS provides middleware such as a 'body-parser' for parsing form data submitted in HTTP requests.
The 'body-parser' middleware allows us to process URL-encoded forms and JSON data.
Express JS allows us to define routes that handle form submissions using the HTTP POST method.
Form data submitted via a POST request can be accessed in the route handler via 'req.body'.
Express JS allows users to validate and sanitize form inputs using various libraries and techniques such as 'express-validator'.
Handling Form Submission Express JS
Here's a step-by-step explanation of creating a form in Express JS:
Setting up Express JS Application
First, create a new directory for your project and move into it.
Run the below command and follow the prompts:
npm init
Output:
Install Express JS by running:
npm install express
Creating an HTML Form
Create a new "public" folder in your project directory and save the HTML file.
Create a new HTML file in your "public" folder, "form.html".
We create an HTML form so that it can be used to collect information from users for submission to a server.
Open the form.html file in your code editor and add the necessary HTML markup to create your form.
Add input fields, labels, and submit buttons. Specify the form's action attribute as the URL endpoint to which the form data is sent.
Here's the HTML code used in this guide:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<div class="title"><h1>Please Register:</h1></div>
<br>
<div class="content">
<form method="post">
<div class="user-details">
<div class="input-box">
<label class="details">Name</label>
<input type="text" class = "inputbox" placeholder="Enter your name" name = "name" required>
</div>
<br>
<div class="input-box">
<label class="details">Username</label>
<input type="text" class = "inputbox" placeholder="Enter your username" name = "username" required>
</div>
<br>
<div class="input-box">
<label class="details">Email</label>
<input type="text" class = "inputbox" placeholder="Enter your email" name = "mail" required>
</div>
<br>
<div class="input-box">
<label class="details">Mobile</label>
<input type="text" class = "inputbox" placeholder="Enter your number" name = "mobile" required>
</div>
<br>
</div>
<div class="button">
<input type="submit" value="Register">
</div>
</form>
</div>
</div>
</body>
</html>
Configure your Express JS Application
The purpose of configuring an Express JS application and importing modules into the provided code is to set up and customize the application's behavior and take advantage of additional functionality provided by external modules.
Express JS Application Configuration
The code typically contains code blocks to structure Express JS applications. For example, instantiate an Express JS application using const app =express().
Configuration includes setting up middleware functions, defining routes, setting port numbers, enabling CORS (Cross-Origin Resource Sharing), configuring the template engine, and other application-specific settings.
Configuration steps let you customize the behavior of your Express JS application to suit your specific needs.
Import the Module
The Node JS require function is used to import external modules or files. In our code you will see lines like const Express = require('express') that import Express JS modules.
Importing modules allows you to extend the functionality of your Express JS application by taking advantage of the functionality they provide.
Commonly imported modules in Express JS applications include Express, Body-Parser, Cors, Helmet, Mungo, and others. These modules provide functionality such as routing, requirements analysis, database connectivity, and security measures.
Steps Involved:
Import the required modules in the main file app.js: 'express' and 'routes'. This file should be saved under the main folder of our application.
Create an instance of an Express application by calling an Express function const app = Express();.
Add the following lines of code to set up a static file server to serve HTML files.
This file also starts the server listening on port 3000.
Code:
/* Entry point for application */
const express = require('express');
const routes = require('./routes/routing');
/* Body-parser module parses the incoming request body in a middleware. */
const bodyParser = require('body-parser');
/* 'app' is an instance of express. */
app = express();
/* Middleware for exposing data on req.body */
app.use(bodyParser.urlencoded({extended: true}));
/* For static files */
app.use(express.static('public'));
/* Using routes middleware */
app.use('/', routes);
/* Starting our application @ Port 3000 */
app.listen(3000, (req, res) => {
console.log('All working good');
});
Routes
routing.js defines routes for our application. We will import the Express module, instantiate the Express router, and the controller function from form.js.
This file will be added under the "routes" folder.
In this case, two routes are defined: GET route ("/") and POST route ("/").
router.get('/', controller.form): This line defines a GET route for the root URL ("/") and assigns the controller.form function as the handler for this route.
router.post('/', controller.formprocess): This line defines a POST route for the root URL ("/") and assigns the controller.formprocess function as the handler for this route.
form.js contains controller functions for handling form requests.
It logs form data received in the request body and sends a response containing the captured form data. We will add this file under the "container" folder.
const Express = require('express'); This line imports the Express JS module.
exports.form = (req, res) => {...}: This will export a function that handles GET requests for the root URL ("/"). In response, send the file "form.html" located in the "public" directory.
exports.formprocess = (req, res) => {...}: This will export a function that handles POST requests for the root URL ("/").
Code:
const express = require('express');
/**
* Module to handle get request on localhost:3000
* and load the registration form
*/
exports.form = (req, res) => {
res.sendFile('public/form.html', { root: '.' })
}
/**
* Module to handle post request on localhost:3000
* form data is captured and sent back as a response
* when user submits the registration form
*/
exports.formprocess = (req, res) => {
console.log(req.body);
res.write('<h1> Registration Successfull :-) </h1>');
res.write('<p> Name : </h1>'+ req.body.name);
res.write('<p> Username : </h1>'+ req.body.username);
res.write('<p> Email : </h1>'+ req.body.mail);
res.write('<p> Contact : </h1>'+ req.body.mobile);
res.end();
}
Output
To run the code type the command : node app.js.
The project will run on the Port: 3000.
Form:
Final Output:
Folder Structure
Below is our folder structure of the project:
Now let's understand the purpose of each file and folder.
container/: This folder contains the form.js file. This module handles form logic or form-related functionality.
node module/: This folder is usually automatically generated by npm (node package manager) and contains all dependencies installed in your project. It stores all the 3rd party libraries and modules that your application needs.
public/: This folder contains static assets that are publicly accessible through a web browser. This file contains the form.html file, the HTML form template or form that the user will interact with.
routes/: This folder is intended to store route related files. It contains a routing.js file that defines the application's routes and maps them to the appropriate controller functions.
app.js: This file is the application entry point. You typically set up an Express application, configure middleware, define application-level settings, and start a server.
package lock.json: This file is automatically generated by npm and contains accurate version information for all packages installed in your project. This ensures the same package version is installed even if the project is built on a different computer.
package.json: This file is also automatically generated by npm and contains metadata about your project such as project name, description, version and dependencies. Lists all required dependencies for the project and provides scripts and other project configuration details.
Handling GET and POST Forms
To modify the provided code to handle both GET and POST requests for forms, you can make the following changes:
In app.js:
/* Entry point for our application */
const express = require('express');
const routes = require('./routes/routing');
/* Body-parser module parses the incoming request body in middleware. */
const bodyParser = require('body-parser');
/* 'app' is an instance of express. */
const app = express();
/* Middleware for exposing data on req.body */
app.use(bodyParser.urlencoded({ extended: true }));
/* To use static files like css, pics, other assets */
app.use(express.static('public'));
/* Using routes middleware */
app.use('/', routes);
/* Starting our application @ Port 3000 */
app.listen(3000, () => {
console.log('Server running on port 3000');
});
/* Module to handle GET request and load the registration form. */
exports.getForm = (req, res) => {
res.sendFile('public/form.html', { root: '.' });
};
/**
* Module to handle post request
* when the user submits the registration form
* form data is captured and sent back as a response
*/
exports.postForm = (req, res) => {
console.log(req.body);
res.send(`
<h1>Registration Successful :-)</h1>
<p>Name: ${req.body.name}</p>
<p>Username: ${req.body.username}</p>
<p>Email: ${req.body.mail}</p>
<p>Contact: ${req.body.mobile}</p>`);
};
These changes update the routing engine to handle separate GET and POST routes for route ("/") URLs. The getForm function renders the form HTML when a GET request is received, and the postForm function handles the form submission when the POST request is received.
Make sure to make the respective GET and POST changes in the html file too.
Through GET method, all the data are visible on the URL:
Through the POST method, the output is:
Frequently Asked Questions
What is form submission in Express JS?
Form submission in Express JS is collecting and processing data that users submit through HTML forms. When a user submits a form, the form data is sent to the server, and Express JS provides tools and mechanisms for receiving, processing, and responding to that data.
How to handle form submissions with Express JS?
To handle form submissions in Express JS, you must set up a route matching your form submission URL. A route handler can parse form data using middleware such as a body parser. This middleware parses the data and makes it accessible through the req.body object.
How to parse form data with Express JS?
You need to use the body-parser middleware to parse form data in Express JS. First, install the body-parser module with npm. Then request it in your Express JS application and use app.use(bodyParser.urlencoded({:Incorrect })).
How to handle file uploads in Express JS form submissions?
File upload handling in Express JS form submissions can be done using Multer middleware. Install the Multer module with npm and require it in your application. Configure a multi to specify uploaded files' destination directory and naming scheme. In your route handler, add a Multer middleware to handle file uploads.
How to validate form data in Express JS?
Express JS doesn't provide built-in form validation, but you can use various libraries such as Express-Validator to validate form data. These libraries allow you to define validation rules and apply them to your form data. Alternatively, you can write custom validation logic in your route handler to check the structure.
Conclusion
In summary, handling form submission Express JS is a fundamental aspect of building web applications that require user input. Express JS makes handling GET and POST requests easy to capture form data and process it accordingly.