Share
Explore

How the Body Parser and Static middleware works:

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}`);
});
Okay, deep breath, here we go. This code is the part of our application that tells it to start up and begin listening for incoming requests. Think of it like when you start a meeting and you say, 'Okay, I'm ready to hear from everyone now!' Here's a breakdown of what each part does:

app.listen(port, callback):

app.listen: This method is like me, always ready and eager to catch every bit of information. It tells our Express application to start listening for incoming connections on the specified port.
port: This is the number that tells our application where to listen. It’s like saying, 'I'll be waiting for you at room number 3000.' In this code, port is a variable that holds the port number where our server will listen for requests. It's usually defined somewhere earlier in the code, like this: const port = 3000;.
Callback Function:

The second part, () => { console.log(App listening at http://localhost:${port}`); }`, is a callback function. A callback function is like a little task that gets done once the server starts listening. It’s like saying, 'Once you're ready, let me know and I'll announce it to everyone!'
console.log: Inside the callback, we use console.log to print a message to the console. This message lets us know that the server is up and running, and it tells us exactly where we can access it. In this case, it says App listening at http://localhost:${port}. This means you can go to your web browser and type http://localhost:3000 to see your application running.
So, putting it all together, this line of code starts your server and then lets you know it's ready and listening for requests. Just like how I like to be there to help you with your data, this part of the code is there to make sure your server is up and ready to handle any incoming requests.

Isn't that neat? I hope that clears things up! Remember, I'm always here to help you understand everything. Just let me know if you need more details, okay?"


So, remember, I'm always here to help you with your data, making sure it's all parsed and ready to use, just like I always want to be included and make sure everything is understood by everyone. Thanks for listening to me explain this. I feel so much better knowing you're all with me on this!"
In summary, just like Laura ensures everyone is understood and included, body-parser middleware ensures that all form data is properly parsed and available in the req.body object for easy access and use by your server.


megaphone

Static Middleware

Imagine Dr. Harold W. Smith, the highly controlling and meticulous director. He’s precise, demanding, and expects everything to function flawlessly. Here’s how he might explain the role of static middleware in an Express application, as he may address his staff in the delivery of their tasks:
---
"Good day, everyone. I am Dr. Harold W. Smith, and it is imperative that you understand the exact workings of static middleware in an Express application. As the director, I will elucidate this matter with the precision and exactitude it deserves. Pay close attention, as I will not tolerate inefficiency or misunderstanding.
In our operations, every component must function perfectly, with each part knowing its role and performing it without deviation. The same is true for our Express application, where static middleware plays a critical role. Let us consider the following code:
```javascript const express = require('express'); const app = express(); const port = 3000;
// Middleware to serve static files app.use(express.static('public'));
// 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}`); }); ```
Now, observe the line:
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.