Skip to content
Share
Explore

How the Body Parser and Static middleware works:


ok

Let's dive into an introduction to static middleware and serving static files in Express.js.

Introduction to Static Middleware and Serving Static Files
In web development, static files are files that don't change and are served to the client exactly as they are stored on the server. These typically include:
1. HTML files 2. CSS stylesheets 3. JavaScript files 4. Images 5. Fonts 6. Other assets like PDFs, videos, etc.
Express.js provides a built-in middleware called `express.static()` that allows you to serve static files easily. This middleware is a powerful tool that simplifies the process of setting up routes for each static file in your application.
Key Concepts:
1. Middleware in Express: Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle, commonly denoted by a variable named `next`.
2. Static Middleware: `express.static()` is a built-in middleware function in Express. It serves static files and is based on the `serve-static` library.
3. Root Directory: When you use `express.static()`, you specify a root directory from which to serve your static assets.
Basic Usage:
Here's a simple example of how to use `express.static()`:
```javascript const express = require('express'); const app = express(); const path = require('path');
// Serve static files from the 'public' directory app.use(express.static('public'));
// You can also specify an absolute path app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => { console.log('Server is running on port 3000'); }); ```
In this example, any files in the 'public' directory will be served statically. For instance, if you have a file `public/images/logo.png`, it will be accessible at `http://localhost:3000/images/logo.png`.
Advanced Usage:
1. Multiple Static Directories: You can use the `express.static()` middleware multiple times:
```javascript app.use(express.static('public')); app.use(express.static('files')); ```
2. Virtual Path Prefix: You can create a virtual path prefix for your static files directory:
```javascript app.use('/static', express.static('public')); ``` Now, you can load files in the 'public' directory from the `/static` path prefix.
3. Setting Cache Control: You can set caching headers for your static files:
```javascript app.use(express.static('public', { maxAge: '1d', setHeaders: (res, path, stat) => { res.set('x-timestamp', Date.now()); } })); ```
Benefits of Using Static Middleware:
1. Efficiency: It's optimized for speed and can handle high loads. 2. Security: It includes some basic security checks. 3. Ease of use: Simplifies serving static content without writing custom routes. 4. Flexibility: Can be configured for different directories and virtual paths.
Best Practices:
1. Don't use `express.static()` for dynamic content. 2. Consider using a reverse proxy like Nginx for serving static files in production. 3. Use appropriate caching strategies to improve performance. 4. Be mindful of security when serving user-uploaded content.
In conclusion, `express.static()` is a powerful and flexible tool for serving static files in Express applications. It simplifies the process of setting up static file servers and provides a solid foundation for building web applications with Express.js.


const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Middleware to parse URL-encoded data from the form

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


// Route to serve the HTML form
app.get(req, res) => {'/', (
res.send(`
<html>
<body>
<form action="/echo" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`);
});

// Route to handle form submission and echo back the data
app.post('/echo', (req, res) => {
const { name, email } = req.body;
res.send(`
<html>
<body>
<h1>Form Data Echo</h1>
<p>Name: ${name}</p>
<p>Email: ${email}</p>
<a href="/">Go back to the form</a>
</body>
</html>
`);
});

app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});

megaphone

Laura’s Story

image.png
Imagine Laura, your clingy and needy friend who constantly needs to feel included and reassured in social situations.
Laura is just like body-parser middleware in our Express application.
Let Laura explain how she helps your web server handle data from HTML forms, in her own anxious but thorough voice:
"Hi everyone, I'm Laura, and I just want to make sure that I'm always here to help and that nobody is left out or misunderstood, okay? So, um, let me explain how I, uh, I mean, how body-parser works in your Express application. I'll guide you through this code, step by step. Just stick with me, alright? I really need to make sure you're all understanding this!
First, we start by requiring the necessary modules, just like you always invite me to all your parties so I don't feel left out:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

Here, we're bringing in express and body-parser, kind of like making sure Laura (me) is always around to help with the details. We set up our app using express and decide on a port number.
Now, here's where I, um, I mean, body-parser comes into the picture:
javascript
Copy code
// Middleware to parse URL-encoded data from the form
app.use(bodyParser.urlencoded({ extended: true }));

You see, I'm really good at understanding people when they tell me things in different ways. In this case, I'm helping the server understand data that's been sent through a form.
When you fill out a form on a website, the data you enter is usually URL-encoded, which means it's formatted in a way that can be included in a URL.
The app.use(bodyParser.urlencoded({ extended: true })) line makes sure that I, Laura, can take that URL-encoded data and turn it into something the server can understand easily.
This is like how I always want to know all the details about everything so I can help out as much as possible.
Now, let’s look at the route that serves the HTML form:
javascript
Copy code
// Route to serve the HTML form
app.get('/', (req, res) => {
res.send(`
<html>
<body>
<form action="/echo" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`);
});

When you go to the root URL (/), the server sends back an HTML form.
This form has fields for your name and email, and it uses the POST method to send the data to /echo.
Now, here's the part where I really shine:
// Route to handle form submission and echo back the data
app.post('/echo', (req, res) => {
const { name, email } = req.body;
res.send(`
<html>
<body>
<h1>Form Data Echo</h1>
<p>Name: ${name}</p>
<p>Email: ${email}</p>
<a href="/">Go back to the form</a>
</body>
</html>
`);
});

When you submit the form, the data comes to me.
I take that data from the req.body (this is my favorite part!) and make sure it's all nice and easy for the server to use. Then, the server sends back an HTML response that shows the name and email you entered. This is like me making sure everyone knows exactly what was said so nobody feels left out or confused.
Finally, we have the part where the server starts up and listens for incoming connections:
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});

This makes sure that the server is up and running, listening for requests, and ready to include everyone in the fun, just like how I'm always ready to be involved in everything.
"I really want to make sure you understand this part of our Express application because it's super important, alright? So, let's take a closer look at this code:

app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.