在 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.VERB
和router.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/