I\'m starting with NodeJS and Express 4, and I\'m a bit confused. I been reading the Express website, but can\'t see when to use a route handler or when to use
Express 4.0 comes with the new Router. As mentioned on the site:
The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
There is a good article at https://scotch.io/tutorials/learn-to-use-the-new-router-in-expressjs-4 which describes the differences and what can be done with routers.
To summarize
With routers you can modularize your code more easily. You can use routers as:
- Basic Routes: Home, About
- Route Middleware to log requests to the console
- Route with Parameters
- Route Middleware for Parameters to validate specific parameters
- Validates a parameter passed to a certain route
Note:
The app.router object, which was removed in Express 4, has made a comeback in Express 5. In the new version, it is a just a reference to the base Express router, unlike in Express 3, where an app had to explicitly load it.