Node.js Tutorial: Built-in Middleware (express.json, express.static)

beginner
20 min

Node.js Tutorial: Built-in Middleware (express.json, express.static)

Welcome back to CodeYourCraft! Today, we're diving into the world of Node.js and exploring two powerful built-in middleware: express.json and express.static. These tools will help you handle JSON data and serve static files, making your Node.js applications more robust and practical. šŸŽÆ

What are Middlewares?

Before we dive into our main topic, let's quickly recap what middleware is. In Express.js, middleware functions are simply functions that have access to the req (Request) and res (Response) objects, and can perform tasks like parsing requests, handling errors, and serving static files. šŸ“

Express.json Middleware

Why do we need it?

When you receive JSON data from a client, it needs to be parsed into a usable JavaScript object. Express.js provides the express.json() middleware to do this automatically for us. šŸ’”

How to use it?

First, you need to import the required module:

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

Then, add the middleware to your application:

javascript
app.use(bodyParser.json());

Now, you can receive JSON data in your endpoints:

javascript
app.post('/data', (req, res) => { const data = req.body; // JSON data });

Example

Here's a complete example demonstrating how to use express.json() to handle a POST request:

javascript
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.post('/data', (req, res) => { const data = req.body; console.log(data); res.send('Data received!'); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });

Express.static Middleware

Why do we need it?

When you want to serve static files like HTML, CSS, or images, Express.js provides the express.static() middleware to simplify the process. šŸ’”

How to use it?

First, you need to import the required module and specify the directory you want to serve:

javascript
const express = require('express'); const app = express(); const path = require('path'); app.use(express.static(path.join(__dirname, 'public')));

Now, if you navigate to http://localhost:3000/your-file.html, Express.js will serve the file located in the public directory.

Example

Here's a complete example demonstrating how to use express.static() to serve static files:

javascript
const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.listen(3000, () => { console.log('Server listening on port 3000'); });

In the public directory, create a your-file.html:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My Page</title> </head> <body> <h1>Welcome to my page!</h1> </body> </html>

Quiz Time! 🧠

Quick Quiz
Question 1 of 1

What is the purpose of the `express.json()` middleware in Express.js?

That's it for today! We've covered the essentials of using express.json() and express.static() in your Node.js projects. As always, keep practicing and exploring! šŸš€

šŸ“ Note: Remember to install the required dependencies using npm:

bash
npm install express body-parser