Setting up Middleware
Introduction to Middleware
In Express.js, middleware functions are used to handle requests, responses and the next middleware function in the application's request-response cycle. Middleware functions can perform tasks like executing any code, making changes to the request and response objects, ending the request-response cycle, or calling the next middleware function in the stack.
Setting Up Middleware
To set up middleware in your Express.js application, you need to use the app.use()
method. This method is used to load the middleware function at a path. The middleware function is executed whenever the base of the requested path matches the path.
Here is a basic example:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
In the example above, a middleware function is set up without a path. Therefore, this middleware function will be executed every time the app receives a request.
Types of Middleware
Application-level middleware: These middleware functions are bound to the app object using the
app.use()
method. They are executed in the order they are defined.Router-level middleware: These middleware functions work in a similar way to application-level middleware, except they are bound to an instance of
express.Router()
.Error-handling middleware: These middleware functions are used to handle errors in your application. They are defined with four arguments instead of three, specifically with a
err
argument first.Built-in middleware: Express has some built-in middleware functions like
express.static
,express.json
, andexpress.urlencoded
.Third-party middleware: You can also use third-party middleware functions by installing via NPM.
Using Middleware
You can specify a path as the first argument to the app.use()
method. The middleware function will then be executed whenever the base of the requested path matches the path.
Here's an example:
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
In the example above, the middleware function will be executed every time the app receives a request to /user/:id
.
Error-Handling Middleware
Error-handling middleware functions are defined in the same way as other middleware functions, except they have four arguments instead of three. Specifically, they have an additional err
argument.
Here's an example:
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
In the example above, the error-handling middleware function is defined. This function will be executed whenever there's an error.
Conclusion
Middleware is a fundamental part of Express.js as it allows you to manage the request-response cycle in your application. You can create your own middleware for custom functionality, or use built-in or third-party middleware.