简体   繁体   English

子路由中 express() 和 express.Router() 之间的 NodeJS 差异

[英]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()我在我的服务器中创建了一个子路由,比如'/users' ,它使用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:但是在mountpath部分的 express 文档中,它使用另一种方式,例如对子路由使用userRoute = express()并在此处将其称为子应用程序:

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.您始终需要使用express()来创建顶级服务器应用程序,但要创建包含隔离的路由块或其他功能的子应用程序,您可以选择安装新的express()应用程序或express.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:如果您查看 Application 和 Router 对象可用的记录属性、方法和事件,您会发现 Application 具有 Router 所具有的所有属性、方法和事件,另外还有一些可以分为四个主要功能区域:

  1. App settings ( get() , set() , disable() , disabled() , enable() , enabled() )应用程序设置( get()set()disable()disabled()enable()enabled()
  2. Templating ( engine() , render() , locals )模板( engine()render()locals
  3. The ability to be notified on being mounted by a parent app (the mount event)在父应用程序安装时收到通知的能力( mount事件)
  4. Access to the path it is mounted at ( mountpath , path() )访问它安装在的路径( mountpathpath()

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.因此,如果您不需要使用这些中的任何一个,或者在某些情况下需要但不需要将它们与父应用程序隔离,那么您可以使用路由器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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