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...