Using Express.js middleware
Express.js provides great ways to write efficient back ends without duplicating code.
Every middleware function receives a request, a response, and next. It needs to run next to pass control further to the next handler function. Otherwise, you will receive a timeout. Middleware allows us to pre- or post-process the request or response object, execute custom code, and much more. We previously covered a simple example of handling requests in Express.js.
Express.js can have multiple routes for the same path and HTTP method. The middleware can decide which function should be executed.
The following code is an easy example showing what can generally be accomplished with Express.js:
- The root path '/' is used to catch any request.
app.get('/', function (req, res, next) {
- We randomly generate a number with Math.random between 1 and 10.
var random = Math.random() * (10 -1) + 1;
- If the number is higher than 5, we run the next('route') function to skip to the next app.get with the same path.
if (random > 5) next('route')
This route will log us 'second'.
- If the number is lower than 0.5, we execute the next function without any parameters and go to the next handler function. This handler will log us 'first'.
else next()
}, function (req, res, next) {
res.send('first');
})
app.get('/', function (req, res, next) {
res.send('second');
})
You do not need to copy this code as it is just an explanatory example. This functionality can come in handy when covering special treatments such as admin users and error handling.