Using Express.js middleware
Express.js provides us with great ways to write efficient backends without duplicating code.
Every middleware function receives a request, a response, and next
. It needs to run next
to pass control 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. Previously, we 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 that shows what can generally be accomplished with Express.js. You can test this by replacing the current app.get
routes:
- The root path,
'/'
, is used to catch any requests:app.get('/', function (req, res, next) {
- Here, we will randomly generate a number with
Math.random
between 1 and 10:var random =...