Node JS Routing and middleware in express js
Routing and middleware are essential concepts in Express.js and Node.js applications. They allow you to define how your application responds to different HTTP requests and how to process these requests before reaching the final route handler. Here’s a detailed explanation of both concepts:
1. Routing in Express.js
Routing refers to the mechanism that determines how an application responds to client requests for specific endpoints. Each route in an Express application is associated with a path and an HTTP method (GET, POST, PUT, DELETE, etc.), and it defines what should be done when a request matches that route.
1.1 Basic Routing
You define routes using methods on the Express application object (app
). For each HTTP method (GET, POST, etc.), you specify the path and a callback function that handles the request.
Example:
const express = require('express');
const app = express();
const port = 3000;
// Define a route for GET requests to '/'
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Define a route for GET requests to '/about'
app.get('/about', (req, res) => {
res.send('About page');
});
// Define a route for POST requests to '/submit'
app.post('/submit', (req, res) => {
res.send('Form submitted');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
1.2 Route Parameters
You can capture values from the URL using route parameters. Parameters are denoted by a colon (:
) in the route path.
Example:
// Define a route with a route parameter
app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);
});
1.3 Query Strings
You can also access query parameters from the URL using req.query
.
Example:
// Define a route with query parameters
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search query: ${query}`);
});
1.4 Route Handling
Express supports multiple handlers for a single route. You can use an array of middleware functions or chain handlers for complex logic.
Example:
// Define multiple handlers for a route
app.get('/example', (req, res, next) => {
console.log('First handler');
next();
}, (req, res) => {
console.log('Second handler');
res.send('Response from the second handler');
});
2. Middleware in Express.js
Middleware functions are functions that have access to the request (req
), response (res
), and the next middleware function in the request-response cycle. Middleware can perform various tasks such as modifying request objects, handling errors, and terminating requests.
2.1 Built-in Middleware
Express provides several built-in middleware functions:
express.json()
: Parses incoming JSON requests.express.urlencoded()
: Parses incoming URL-encoded requests.express.static()
: Serves static files from a directory.
Example:
// Middleware to parse JSON bodies
app.use(express.json());
// Middleware to serve static files from the 'public' directory
app.use(express.static('public'));
2.2 Custom Middleware
You can create your own middleware functions to perform custom processing.
Example:
// Custom middleware to log request details
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
});
2.3 Middleware Chaining
You can chain multiple middleware functions to process requests in a sequence.
Example:
// Middleware for authentication
app.use((req, res, next) => {
if (req.isAuthenticated()) {
next(); // User is authenticated, proceed to the next middleware
} else {
res.status(401).send('Unauthorized');
}
});
// Middleware for handling requests
app.use((req, res) => {
res.send('Authenticated request');
});
2.4 Error-Handling Middleware
Error-handling middleware is defined with four arguments: err
, req
, res
, and next
. It’s used to handle errors that occur during request processing.
Example:
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Summary
- Routing: Defines how your application responds to different HTTP requests. You can define routes using HTTP methods (GET, POST, etc.) and specify paths and handlers.
- Route Parameters: Capture dynamic values from the URL.
- Query Strings: Access query parameters from the URL.
- Middleware: Functions that process requests and responses. They can be built-in, custom, or error-handling middleware.
- Middleware Chaining: Allows for sequential processing of requests.
- Error-Handling Middleware: Handles errors in the application.