简体   繁体   中英

NodeJS diffrence between express() and express.Router() in sub routes

I create a sub route in my server like '/users' and it uses userRoute = express.Router()

But in express document in mountpath part it use another way like a use userRoute = express() for sub route and call it sub app here it is:

var app = express(); // the main app
var admin = express(); // the sub app
...
app.use('/admin', admin); // mount the sub app

What are their difference and usage?

感谢jfriend00,当我使用app而不是router我可以设置特定的主题引擎或...为我的路线。

You always need to use express() to create the top-level server app, but to create sub-apps containing isolated blocks of routes or other functionality you can choose between mounting a new express() app, or an express.Router() Router.

The difference between these is in the amount of specific functionality provided to that block; Routers are simpler and focus mainly only on routing, and may be enough in many cases where you just want to logically organise your application. If you look at the the documented properties, methods & events available to both the Application and Router objects, you see that Application has all the ones that Router does, with additional ones that can be grouped into four main areas of functionality:

  1. App settings ( get() , set() , disable() , disabled() , enable() , enabled() )
  2. Templating ( engine() , render() , locals )
  3. The ability to be notified on being mounted by a parent app (the mount event)
  4. Access to the path it is mounted at ( mountpath , path() )

So if you don't need to use any of these, or in some cases do but don't need them to be isolated from the parent app, then you can use a Router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM