javascript - 在 Express 中路由时,应用程序级和路由器级中间件有什么区别?

标签 javascript node.js express url-routing

Express docs ,它说:

Application level middleware are bound to an instance of express, using app.use() and app.VERB().

Router level middleware work just like application level middleware except they are bound to an instance of express.Router(). The middleware system created at the application level in the example above, can be replicated at the router level using the following code.

在Express生成器提供的app中,我看到在主app.js中,有:

var routes = require('./routes/index');
app.use('/', routes);

./routes/index.js 中,我看到了这个:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

app.use 将其传递给 router.get 而不是简单地使用 app.get 的目的是什么?而且一般来说,app.VERBrouter.VERB在路由方面有什么区别?

最佳答案

What is the purpose of app.use passing it to router.get instead of simply using app.get?

这一切都只是为了模块化而设计。它允许将应用程序分成几个较小的松散耦合部分,并且因为它们都没有任何直接了解将它们组合在一起的共享 app 实例,所以实现了模块化。

例如,您可以构建一个完整的用户帐户子系统来处理注册、登录、忘记密码等,并通过 app.use(require( "我的用户系统")).

这是其背后的唯一目的。其他方面没有功能、技术或性能差异。

And generally, what's the difference between app.VERB and router.VERB in terms of routing?

没有区别。该应用程序有自己的主/主路由器,app.VERB 只是相当于 app.router.VERB 的便利糖。

关于javascript - 在 Express 中路由时,应用程序级和路由器级中间件有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29457008/

相关文章:

javascript - 如何调用Javascript函数

javascript - 在angularjs中为这个HTTP GET添加HTTP基本认证

node.js - 如何使用Gun作为快速路线?

node.js - MongoDB Node Express GET 和 DELETE 工作,而不是 POST?

css - ExpressJS 的 Assets

node.js - 无法对 Mongoose 查询进行排序

javascript - DataTables:如何将类设置为表格行单元格(而不是表格标题单元格!)

javascript - 获取数组中计数为偶数或计数大于2的元素

node.js - 在Node.js中,使用async/await处理错误的正确方法是什么?

javascript - 简单的 TCP 聊天 node.js