Node.js Express.js Framework

Introduction to Express.js:

Built on top of Node.js’s HTTP module, Express.js is an additional layer that helps to simplify routes, middleware and other components of web applications.

It is famed for its minimalist design and flexibility which enable developers to create web apps fast and efficiently.

Routing with Express.js:

In essence, you can use Express.js to define routes for handling several types of HTTP methods and URLs.

The routes are defined using the app.METHOD() functions where METHOD represents different HTTP methods like GET, POST, PUT or DELETE.

                                                    
                                                    const express = require('express');
const app = express();

// Handling GET requests
app.get('/', (req, res) => {
    res.send('Home Page');
});

// Handling POST requests
app.post('/users', (req, res) => {
    res.send('User Created');
});

// Handling dynamic routes
app.get('/users/:id', (req, res) => {
    const userId = req.params.id;
    res.send(`User ID: ${userId}`);
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});
                                                    
                                                

In this example we define a route for handling GET requests at the root URL (/), another one for POST requests to /users and dynamic ones that fetch user details based on the id parameter.

Middleware in Express.js:

They are middleware functions in Express.js that have access to req (request object) res (response object) as well as next middleware function in an application request-response cycle.

They can do things such as parsing request bodies, logging, authentication, error handling etc.

                                                    
                                                    const express = require('express');
const app = express();

// Custom middleware function
const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next(); // Call the next middleware function
};

// Registering middleware globally
app.use(logger);

// Route-specific middleware
app.get('/admin', (req, res, next) => {
    if (req.query.admin === 'true') {
        next(); // Call the next middleware function
    } else {
        res.status(403).send('Access Forbidden');
    }
});

app.get('/admin', (req, res) => {
    res.send('Admin Panel');
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});
                                                    
                                                

In this example we define a custom middleware function logger that logs the HTTP method and URL of incoming requests. We attach it globally through app.use() so it runs for every incoming request.

We register this middleware globally using app.use(), so it will be executed for every incoming request. Additionally, we define route-specific middleware to restrict access to the /admin route based on a query parameter.