02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Routing with Forms and Static Files in Express.js

Routing with Forms and Static Files in Express.js

In this tutorial, we will explore how to create dynamic routes using forms and static files in Express.js. This process will help us serve dynamic content based on user input, which is crucial for building interactive web applications. Let's dive into it!

Setting Up the Basics

Step 1: Preparing the Project Structure

First, we need to create a directory structure for our project. To keep things organized, let's create a private folder to store HTML files that are not publicly accessible.

Open a terminal, and run the following commands:

mkdir private
cd private
touch form.html

This will create a new folder named private and an HTML file called form.html. We'll use this HTML file to design a simple form.

Step 2: Creating the Form

Open form.html in your favorite code editor, and add the following basic HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form</title>
  <style>
    body {
      background-color: pink;
    }
  </style>
</head>
<body>
  <form action="/form" method="post">
    <input type="text" name="name" value="">
    <button type="submit">Post</button>
  </form>
</body>
</html>

The form will have an input field for the user's name and a submit button that will trigger a POST request to our server.

Adding the Form Route in Express.js

Now that we have our form, let's configure our Express.js server to serve this form and process its data.

Step 3: Setting Up the Server

Make sure you have Node.js and Express installed in your project. If not, run:

npm init -y
npm install express

Open the main file of your Express application (e.g., index.js) and set up the necessary routes.

const express = require('express');
const path = require('path');
const app = express();

// Middleware to parse request body
app.use(express.urlencoded({ extended: true }));

// Route to serve the form
app.get('/form', (req, res) => {
  res.sendFile(path.join(__dirname, 'private', 'form.html'));
});

// Route to handle form submissions
app.post('/form', (req, res) => {
  const { name } = req.body;
  res.send(`Hello, ${name}! This is your submitted data.`);
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Explanation

  1. Middleware: We use express.urlencoded() to parse incoming request bodies, which is necessary for handling form data in a POST request.
  2. GET Route: The GET route /form serves the HTML file containing our form.
  3. POST Route: The POST route /form handles form submissions and responds with a personalized greeting using the form data.

Step 4: Testing the Application

To test the application, start the server by running:

node index.js

Then, navigate to http://localhost:3000/form in your browser. You should see the form we created. Enter a name and hit the "Post" button to see the server's response.

Notes on Middleware

In Express.js version 4 and above, several built-in middleware functions, such as body parsers, were removed from the core library and moved to separate modules. Here, we use express.urlencoded() as middleware to parse form data.

Note: If you're using an older version of Express (pre-4.0), you may need to include the body-parser middleware explicitly.

npm install body-parser

And include it in your code like this:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

Updates Since 2016

  • Express Middleware: Since 2016, Express.js integrated middleware like express.json() and express.urlencoded() directly into the core library, making it easier to handle different request data types.
  • Security Considerations: When handling forms and user input, always be mindful of security best practices such as input validation and sanitization to avoid XSS or injection attacks.

Conclusion

In this tutorial, we covered how to create a basic form, serve it using Express.js, and handle dynamic form submissions. Routing in Express.js makes it easy to serve both static and dynamic content, which is essential for creating interactive web applications.

Feel free to experiment by adding more fields to the form and expanding the application logic to handle more complex scenarios!

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!

Starting up an Express.js server

Learn how to start up an Express.js server, including installation, basic setup, and creating a Hello World server.

08:08

Enabling static files

Learn how to enable static files in Express.js to serve HTML, CSS, JavaScript, and other assets in your web application.

04:47

Routing with Express

In this video, explore the basics of routing in Express.js and how to create dynamic content. Learn about GET, POST, PUT, DELETE, and how to handle different routes effectively.

09:08

Routing with Forms and Static Files in Express.js

Learn how to create dynamic routes with forms and static files using Express.js. This is essential for building interactive web applications.

06:14

Using Middleware in Express.js

Learn how to integrate third-party middleware in Express.js, specifically using body-parser, to handle form data and extend server functionality.

07:29

Creating a middleware in ExpressJS

Learn how to create your own middleware in ExpressJS to handle custom server-side logic and responses.

03:54

Using Express Generator

Learn how to quickly scaffold Express.js applications using the Express Generator tool. This tool helps automate server setup and structure, making development faster and easier.

04:34

Back to React

Learn about integrating Webpack and Babel with React to streamline full stack development.

18:16