• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Handling Forms with Express: A Comprehensive Tutorial

  • June 24, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial ->
  • Setting up Express Project
  • Creating a Basic Form
  • Handling Form Submission
  • Starting the Application
Handling forms in Express
Handling forms in Express

Handling forms is a fundamental aspect of web development. In this tutorial, we will explore how to handle forms efficiently in Express, a popular Node.js web framework. We will cover essential concepts such as form submission, data validation, error handling. By the end of this tutorial, you will have a solid understanding of how to build robust and user-friendly forms in Express. Let’s Start



Setting up Express Project

1. Create a new directory for your project and navigate to it in your terminal:

mkdir express-app
cd express-app

2. Initialize a new npm project by running the following command and following the prompts:

npm init

3. Install Express as a dependency:

npm install express

4. Create a file named app.js (or any other preferred name) in the project directory. This will be the entry point of your Express application.

5. Open app.js in a code editor and add the following code to set up a basic Express application:

// Import the required modules
const express = require('express');
const app = express();
const port = 3000; // Choose your preferred port number

// Set up a route for the homepage
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

6. Save the file and go back to your terminal.

7. To start the Express application, run the following command:

node app.js

Once the server is up and running, you will see following message in the console:

‘Server is running on port 3000’

Open your web browser and visit http://localhost:3000 (replace 3000 with the port number you chose in the code). You should see the message “Hello, Express!” displayed in the browser.

Hello Express
Hello Express

You can stop this server by pressing CTRL+C.



Creating a Basic Form

To handle form submissions in Express, you first need to create a basic HTML form that users can interact with. Here’s an example of how to create a basic form using HTML:

<form action="/submit" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <button type="submit">Submit</button>
</form>

In this example, we have a simple form that collects the user’s name and email address. The form’s action attribute is set to “/submit”, which represents the route in Express that will handle the form submission. The method attribute is set to “POST” to indicate that the form data should be sent as a POST request.

Make sure to include appropriate input fields and labels for the form fields you require. Use the name attribute on input fields to identify them when handling the form submission.

We want this form to be displayed as our homepage ie localhost:3000.

Next, let’s move on to handling the form submission in Express.

Handling Form Submission

When working with forms in Express, it is essential to handle form submissions properly. This involves defining a route to handle the form submission request, extracting the form data, and implementing the necessary logic to process and respond to the submitted data.

To handle form submissions in Express, follow these steps:

a. Define the Route: Start by defining a route in your Express application that corresponds to the form’s action attribute. This route should handle the HTTP POST request sent when the form is submitted. For example:

app.post('/submit', (req, res) => {
  // Handle form submission logic here
});

In this example, the route is /submit, but you can choose any URL path that suits your application’s requirements.

b. Extract the Form Data: To access the submitted form data, you need to use middleware to parse the request body. One popular middleware for this purpose is body-parser. Install it by running the following command:

npm install body-parser

Once installed, import and use the middleware in your Express application:

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));

The urlencoded method of body-parser parses the form data sent in the request body and makes it accessible via the req.body object.

The extended: false option in the bodyParser.urlencoded() middleware configuration determines how the request body data is parsed.

When extended is set to false, the body-parser middleware uses the built-in querystring library to parse the URL-encoded data in the request body. This parsing mode treats the data as a nested object or array format.

For example, with extended: false, the URL-encoded form data:

name=John&age=30

will be parsed into an object:

{ name: 'John', age: '30' }

Setting extended to true would enable parsing of more complex data structures, such as arrays and objects nested within the form data.

However, for most use cases, setting extended: false is sufficient, as it covers the common scenario of processing simple form submissions with key-value pairs.



c. Implement the Form Submission Logic:

Inside the route handler for form submission (/submit in this example), you can access the form data using req.body. Process the form data according to your application’s requirements. For instance, you can perform database operations, send emails, or perform any other necessary actions.

Here’s an example of handling a form submission and logging the submitted data:

app.post('/submit', (req, res) => {
  const name = req.body.name;
  const email = req.body.email;

  // Process the form data
  console.log(`Submitted Name: ${name}`);
  console.log(`Submitted Email: ${email}`);

  // Send a response to the client
  res.send('Form submitted successfully!');
});

In this example, the form data is extracted from req.body, and the name and email fields are logged to the console. You can replace the console logs with your custom logic.

d. Respond to the Client: After processing the form data, you can send a response back to the client to acknowledge the successful submission or provide any additional information. Use the res.send() method to send a response to the client.

For example, the code snippet above sends the response message “Form submitted successfully!” back to the client.

To ensure that we are on same page, here are some inputs

Folder Structure
app.js
// Import the required modules
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const port = 3000; // Choose your preferred port number
app.use(bodyParser.urlencoded({ extended: false }));

// Set up a route for the homepage 
// we want the form to be displayed on home page

app.get('/', (req, res) => {
  res.sendFile(__dirname+'/views/form.html'); // we use sendFile to display the html page.
});

// Set up route for form submission
app.post('/submit', (req, res) => {
    const name = req.body.name;
    const email = req.body.email;
  
    // Process the form data
    console.log(`Submitted Name: ${name}`);
    console.log(`Submitted Email: ${email}`);
  
    // Send a response to the client
    res.send('Form submitted successfully!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
form.html
<form action="/submit" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
  
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
  
    <button type="submit">Submit</button>
</form>

By following these steps, you can effectively handle form submissions in your Express application. Remember to customize the form submission logic to suit your specific requirements, such as storing data in a database or triggering certain actions based on the submitted form data.



Starting the Application

a. Open your terminal and run following command

node app.js

You will see following message in the console: Server is running on port 3000

Note – Please make sure that you have installed html module as well via npm.

b. Open your browser and navigate to http://localhost:3000/. You will see the content of form.html is being displayed on that page.

HTML FORM
HTML FORM

c. Enter the details as per your wish.

Fill up the form

d. Click on submit. Once you submit this form, a post request ( as in form.html we have defined form method as post) will be sent to ‘/submit’ route which will then do the needful.

e. See the terminal to check whether you were able to catch those values.

Output
Output

That’s all.





Keywords to search for: Express form handling tutorial, Handling forms in Express.js,
Form submission with Express, Express form validation, Handling form data in Express, Express form handling best practices, Express form handling middleware, Handling file uploads in Express forms, Client-side form validation with Express,Express form handling examples, Express form handling tutorial, Handling HTML forms in Express.js, Form validation with Express, Handling form submission in Express, Express form handling best practices, Client-side form validation with Express, Express form data processing, Dynamic forms with Express.js, File uploads with Express forms, Redirecting after form submission in Express,

Tags: Client-side form validation with ExpressDynamic forms with Express.jsExpress form data processingExpress form handling best practicesExpress form handling examplesExpress form handling middlewareExpress form handling tutorialExpress form validationFile uploads with Express formsForm submission with ExpressForm validation with ExpressHandling file uploads in Express formsHandling form data in ExpressHandling form submission in ExpressHandling forms in Express.jsHandling HTML forms in Express.jsRedirecting after form submission in Express
  • Previous File Uploads with Forms in Express: A Step-by-Step Tutorial
  • Next Serving Static Files in Express: A Complete Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.