In Express.js, middleware functions are the core building blocks for handling requests and responses. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the applicationβs request-response cycle.
Middleware can perform tasks such as executing code, modifying the request and response objects, ending the request-response cycle, or calling the next middleware in the stack. Express applications are essentially a chain of middleware functions that are executed in the order they are defined.
This middleware is bound to the instance of the Express application using app.use() or app.METHOD().
const express = require('express');
const app = express();
// Middleware function
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.get('/', (req, res) => {
res.send('Hello from the root route!');
});
app.listen(3000);
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().
const express = require('express');
const router = express.Router();
router.use((req, res, next) => {
console.log('Request URL:', req.originalUrl);
next();
});
router.get('/user', (req, res) => {
res.send('User route');
});
const app = express();
app.use('/api', router);
app.listen(3000);
Express includes several built-in middleware functions starting from version 4.x such as:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/data', (req, res) => {
res.json(req.body);
});
app.listen(3000);
These are middleware modules created by the community and installed via npm. Examples include morgan, cors, helmet, and body-parser.
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Logging HTTP requests with Morgan');
});
app.listen(3000);
Error-handling middleware has four parameters: err, req, res, and next. It must be defined after all other app.use() and route calls.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Something went wrong!');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000);
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
app.use(logger);
app.get('/', (req, res) => {
res.send('Middleware example with custom logger');
});
Middleware functions execute in the order they are defined. This is crucial for correct behavior, especially for parsing, logging, and error handling.
app.use(middleware1);
app.use(middleware2);
app.get('/', (req, res) => {
res.send('Final route handler');
});
Middleware is at the heart of Express.js. It provides a powerful and flexible way to intercept and manipulate requests and responses. Whether youβre logging data, validating input, handling errors, or adding custom functionality, middleware allows you to modularize and control your applicationβs behavior at every stage of the request-response cycle.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved