【问题标题】:What does route('next') do in ExpressJS?ExpressJS 中的 route('next') 有什么作用?
【发布时间】:2015-05-30 01:39:13
【问题描述】:

documentation 中写道:

您可以提供多个回调函数,其行为类似于中间件,除了这些回调可以调用 next('route') 以绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,然后如果没有理由继续当前路由,则将控制权传递给后续路由。

这是否意味着如果我写这样的路线:

app.get('/', function(req, res, next) {
    if (!req.params.id) {
        res.statusCode(400).send({error: "id parameter is required"});
        next('route');
    } else {
        next();
    }
}, function(req, res) {
    res.send({something: 'something'})
});

params.idundefined,则不会执行下一个路由,但如果它存在,它会执行吗?

基本上,编码/命名约定让我有点困惑。为什么不用next(false) 而不是next('route')

【问题讨论】:

标签: javascript node.js express


【解决方案1】:

我找到了答案。使用app或Express路由器时,可以为同一路径定义多条路由:

// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
  // logic
}, function (req, res, next) {
  // logic
});

// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
  // logic
});

如果从第一条路由的任何回调(中间件)调用next('route')路由集的所有回调将被跳过并控制被传递到下一组路由:

// first set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
  next('route')
}, function (req, res, next) {
  // this middleware won't be executed at all
});

// second set of routes for GET /user/:id
app.get('/user/:id', function (req, res, next) {
  // the next('route') in the first callback of the first set of routes transfer control to here
});

现在使用next('route') 而不是next(false) 更有意义:它将控制权转移到为当前路径定义的下一条路径。

【讨论】:

    【解决方案2】:

    (if) params.id 未定义,那么下一条路由不会是 执行,但如果它存在,它会吗?

    关键思想是文件中的下一个路由将被选中

    来自duplicate question,它更详细地回答了这个问题:

    next() 没有参数说“开个玩笑,我真的不想 处理这个”。它返回并尝试找到下一条路线 会匹配。

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 2023-02-06
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多