Differences between express.Router and app.get?

前端 未结 8 1037
终归单人心
终归单人心 2020-11-29 14:24

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

8条回答
  •  我在风中等你
    2020-11-29 14:47

    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:

    1. Basic Routes: Home, About
    2. Route Middleware to log requests to the console
    3. Route with Parameters
    4. Route Middleware for Parameters to validate specific parameters
    5. 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.

提交回复
热议问题