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

时间:2015-04-05 11:57:01

标签: javascript node.js express url-routing

Express docs中,它说:

  

应用程序级中间件绑定到express的实例,使用app.use()和app.VERB()。

     

路由器级中间件就像应用程序级中间件一样工作,除了它们绑定到express.Router()的实例。在上面的示例中,在应用程序级别创建的中间件系统可以使用以下代码在路由器级别进行复制。

在Express生成器提供的应用程序中,我在主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在路由方面的区别是什么?

3 个答案:

答案 0 :(得分:21)

  

app.use将目的传递给router.get的目的是什么,而不是简单地使用app.get?

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

例如,您可以构建一个整个用户帐户子系统来处理注册,登录,忘记密码等,并通过" mount"在几个不同的应用程序之间共享它。它通过app.use(require("my-user-system"))

这是背后的唯一目的。否则没有功能,技术或性能差异。

  

一般来说,app.VERB和router.VERB在路由方面的区别是什么?

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

答案 1 :(得分:8)

一个例子在这里会有所帮助:

在birds.js中:

// birds.js

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

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
    console.log('Time: ', Date.now());
    next();
});
// define the home page route
router.get('/', function (req, res) {
    res.send('Birds home page');
});

在app.js中:

// app.js

const express = require('express')
const app = express()

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

app.listen(3000, () => console.log('app listening on port 3000!\naccess http://localhost:3000/birds/'))

现在向http://localhost:3000/birds/的请求将转到birds.js文件。

随着应用程序变得越来越大,这种模块化方法将使维护大量代码库变得容易。

来源:https://expressjs.com/en/guide/routing.html

答案 2 :(得分:1)

应用程序具有方法 listen 和其他一些路由器所没有的方法。

应用程序“做”主要的事情,而路由仅将某些路由分组,提供了封装(请参阅Manohar的示例示例)。

路由器中的路由不一定预先知道完整的路由。在示例中看到,“ / birds”在app.js中定义,这是bird.js中路由器的根目录。app.VERB和rourer.VERB之间的区别在于上下文。