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!

Video Transcript

00:00In the last lecture, we got familiarized
00:03with the concept of routes.
00:05We're not gonna walk away from
00:06that term altogether, as in the process.
00:08Now we're gonna go ahead and create a form
00:11or start creating that form,
00:13but we really want to send different information in
00:15that form in the beginning stage
00:17before the user put in any content
00:19versus when the user completed the content
00:21and everything is okay.
00:23So we're gonna go ahead and take a look at
00:25how do we respond to forms?
00:26How do we route forms, those different types of usages?
00:30And beyond that, we're also gonna take a look at
00:32how do we respond with a static file for the different types
00:36of scenarios.
00:37So let's jump right into it
00:38and let's start building out our form.
00:42Okay, so what I want to do next is I want
00:44to create a private file that is not accessible to the web
00:48and I wanna be able to use it
00:51and send it to our form as a file, as the, as a response
00:55whenever a request for a form happens.
00:58So to be able to do that,
00:59I'm gonna go into my terminal again
01:01and what I wanna do is I'm gonna, I'm gonna exit my server,
01:03killing it once I killed my server.
01:06What I wanna do is I want to go ahead
01:08and mk dear, I'm gonna create a new folder.
01:10I'm gonna call it private and I'm gonna go into my
01:14private folder.
01:16Or you know what, let me just go ahead and touch private
01:20and we're gonna call this form html.
01:25I've created a form, it's sitting in a private folder.
01:28If I go back into my, um, if I go back into my folders,
01:31you'll see I'll have your private with a form.
01:33Let's go ahead and open it up inside of our editor.
01:36So I'm just gonna go ahead here
01:38and just toss it into our editor.
01:40And what I want to do next is I want to go ahead
01:42and create the form.
01:43So I'm gonna step through the basics
01:46of creating an HTML document.
01:48So I'll just go ahead and paste that in there.
01:50And this is, let's just give you a title form.
01:54Let's give it a nicer color pink.
01:57And let's go ahead and let's create the form.
01:59So first of all, I'm gonna create the form tag
02:02and my action is gonna be a action
02:05that sends it to the form back.
02:06So I'm sending it back to itself,
02:08or if it's in a different place, it will go
02:09to the action of form.
02:12And the method that I'm gonna be using is gonna be a post
02:15method, could have used a get as well.
02:19But in this case, we wanna activate
02:21and you want to reach inside of our controller.
02:24We basically wanna reach the post area.
02:25So I'm using a post command in our form.
02:29Okay, so I'm just gonna Peter some simple stuff.
02:31I'm gonna go ahead and put here a new input
02:33and I'm gonna give it a name.
02:35I'm gonna set the name to be, just name
02:38and I'm gonna set a value to be, uh,
02:41let's just set it to be a name as well.
02:43And lemme go ahead and create here a quick button
02:48that will enable the users to submit the button.
02:52And let me just give it a name.
02:54So how about we just call this post
02:57because we're posting things.
02:59Alright, so we saved the file. We have a form html.
03:03All that's left for me to do is inside of my,
03:06uh, request itself.
03:08'cause this is when we want to do it.
03:09Instead of sending here text using the send command,
03:12I'm going to use the response send file instead
03:16of sending a specific text in a string.
03:19And I'm gonna use a global variable, which is called un
03:24underline, underline Dear name, which is the directory name
03:29that we're currently in.
03:30And I'm con, I'm gonna conta concatenate it with our
03:35private folder.
03:38And in it, I want to get our form html.
03:41So what I'm doing here is I'm connecting them together
03:43and sending in that full directory path.
03:46Now, by the way, if you're working with an older version
03:48of Express Datas, this wouldn't work
03:50because Send File has only been around since
03:53Express version 4.8 and onwards.
03:56So make sure that if, as you're watching this title,
03:59'cause we're running on no JS version six
04:01and we're working with, with Express with one
04:03of the latest versions as well.
04:05So I'm gonna go ahead here and save this file.
04:07And all that's left for me to do is to restart my server.
04:11So lemme go ahead here and restart my server.
04:13So I'm gonna get out of my server, let me clear our screen,
04:17and I'm gonna go ahead and restart our server.
04:20Now that our server is running, if I go ahead here
04:23and click here on Refresh, we'll see
04:24that now we're getting a form.
04:26That form is the form that we've created previously.
04:28So my name is Ben, I'm gonna post it
04:30and our results will come in
04:32and we're gonna get finally access to our post area.
04:36Now, what I would wanna really do is actually get that name
04:40that we've just had in our form.
04:42'cause our form has here a name
04:44and I want to be able to use it within our post.
04:46Maybe for now, let's just say hello to it
04:48or let's put the name within.
04:51Now, in earlier versions of Express js,
04:54when I'm saying earlier, that means three
04:55and below, there was a built-in mechanism to enable you
04:59to gain access to the, to these parameters.
05:03These post parameters as of express JS four
05:06and onwards, really part of that process.
05:09Part of that core philosophy behind express JS is that
05:14any function, it, it wants to be basically a dumb,
05:17you could say, a dumb system that doesn't,
05:20that doesn't define how you work with things.
05:23And to do that, the idea was to extract out functionalities
05:27and this hand them over to different libraries
05:30where you would, they call them middlewares.
05:32And these middlewares would then be able
05:34to basically take over that role.
05:37So built in, we have no way of doing it, but worry not
05:40because in the next lecture we're gonna take a look at
05:42how do we actually add middlewares into an express js,
05:47the express JS framework really to enable us to add,
05:50ADD functionality that will let us gain access
05:53to this data. In this lecture,
05:57So far we started building out a form
05:59and have responded with static files in the next lecture,
06:02we want to continue the process of creating our form
06:06as we start using middlewares to be able to solve a problem
06:09that we have that we can't solve without the help of
06:12that middleware.

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!