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
- Middleware: We use
express.urlencoded()
to parse incoming request bodies, which is necessary for handling form data in aPOST
request. - GET Route: The
GET
route/form
serves the HTML file containing our form. - 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()
andexpress.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!