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. šÆ
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. š
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. š”
First, you need to import the required module:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');Then, add the middleware to your application:
app.use(bodyParser.json());Now, you can receive JSON data in your endpoints:
app.post('/data', (req, res) => {
const data = req.body; // JSON data
});Here's a complete example demonstrating how to use express.json() to handle a POST request:
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');
});When you want to serve static files like HTML, CSS, or images, Express.js provides the express.static() middleware to simplify the process. š”
First, you need to import the required module and specify the directory you want to serve:
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.
Here's a complete example demonstrating how to use express.static() to serve static files:
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:
<!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>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:
npm install express body-parser