One of the most important things about Express.js is how minimal this framework is. Known for its simplicity and performance, Express.js is one of the most popular frameworks in the Node.js ecosystem.
Let's dive into interesting parts:
Using Middleware functions, is possible to access the request and response objects, making it easy to add functionalities like logging, authentication, and data parsing. Check the example:
const requestLogger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
};
The next() function, is responsible to pass the control for the next middleware. Without calling this function, the request will not proceed to the next middleware or route handler, and the request-response cycle will be left hanging.
You can also apply this middleware for all the routes, using only a line of code.
app.use(requestLogger);
This show to how Express.js is really simple to read! 😁
Testing
This is my favorite part, let's test it!!
Adding some basic routes to test the middleware
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
Follow the full code for test the Middleware functions:
Note: Create a file 'index.js' and add the full code.
const express = require('express');
const app = express();
const port = 3000;
const requestLogger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
};
app.use(requestLogger);
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
IMPORTANT
Before run check if the port in the const port
is in use.
Run in the terminal:
node app.js
Thank you, Please Follow: Webcrumbs
Bibliography: Express.js Docs
Top comments (0)