【问题标题】:Hierarchical routing with plain Express.js使用普通 Express.js 的分层路由
【发布时间】:2014-04-28 04:06:43
【问题描述】:

我正在使用 Node 和 Express 实现一个 RESTful API。说到路由,目前是这样的:

var cat = new CatModel();
var dog = new DogModel();

app.route('/cats').get(cat.index);
app.route('/cats/:id').get(cat.show).post(cat.new).put(cat.update);

app.route('/dogs').get(dog.index);
app.route('/dogs/:id').get(dog.show).post(dog.new).put(dog.update);

我不喜欢这个有两个原因:

  1. 无论我是否需要,都会实例化 cat 和 dog 模型。
  2. 我必须为每个路径模式重复 /cats 和 /dogs

我很想拥有这样的东西(当然不行):

app.route('/cats', function(req, res)
{
    var cat = new CatModel();

    this.route('/').get(cat.index);
    this.route('/:id').get(cat.show).post(cat.new).put(cat.update);
});

app.route('/dogs', function(req, res)
{
    var dog = new DogModel();

    this.route('/').get(dog.index);
    this.route('/:id').get(dog.show).post(dog.new).put(dog.update);
});

在没有任何其他模块的现代 Express 中是否有一种干净的方式(如 express-namespace)?我可以为每个型号选择单独的路由器,并为它们分配app.use('/cats', catRouter)。但是,如果我有多个层级,例如'/tools/hammers/:id',该怎么办?然后我会在路由器中的路由器中拥有路由器,这对我来说似乎有点过头了。

【问题讨论】:

    标签: node.js routes url-routing


    【解决方案1】:

    然后我会在路由器中的路由器中使用路由器,这对我来说似乎有点过头了。

    也许吧,但那是在app.use()Router() 前加前缀的内置方法。

    var cats = express.Router();
    app.use('/cats', cats);
    
    cats.route('/').get(cat.index);
    cats.route('/:id').get(cat.show).post(cat.new).put(cat.update);
    
    // ...
    

    并且,有一个Router .use() 另一个来定义多个深度:

    var tools = express.Router();
    app.use('/tools', tools);
    
    var hammers = express.Router();
    tools.use('/hammers', hammers);
    
    // effectively: '/tools/hammers/:id'
    hammers.route('/:id').get(...);
    

    不过,为了更接近您的第二个 sn-p,您可以定义一个自定义方法:

    var express = require('express');
    
    express.application.prefix = express.Router.prefix = function (path, configure) {
        var router = express.Router();
        this.use(path, router);
        configure(router);
        return router;
    };
    
    var app = express();
    
    app.prefix('/cats', function (cats) {
        cats.route('/').get(cat.index);
        cats.route('/:id').get(cat.show).post(cat.new).put(cat.update);
    });
    
    app.prefix('/dogs', ...);
    
    app.prefix('/tools', function (tools) {
        tools.prefix('/hammers', function (hammers) {
            hammers.route('/:id').get(...);
        });
    });
    

    【讨论】:

    • 一流的答案!尤其是您的第二个示例,进一步推动了我的 JavaScript/Node 技能。
    【解决方案2】:

    查看 Express 4 中的 new Router。这听起来正是您想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2015-12-17
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      相关资源
      最近更新 更多