【问题标题】:Stop middleware pipeline execution in KOA在 KOA 中停止中间件管道执行
【发布时间】:2015-08-25 13:36:02
【问题描述】:

请问有没有办法在KOA中停止中间件管道的执行?

在下面的示例中,我有一个可以以某种方式验证某些内容的中间件。验证失败时如何重新编码中间件以停止执行?

var koa = require('koa');
var router = require('koa-router')();
var app = koa();

app.use(router.routes());

// middleware
app.use(function *(next){
  var valid = false;
  if (!valid){
    console.log('entered validation')
    this.body = "error"
    return this.body; // how to stop the execution in here
  }
});

// route
router.get('/', function *(next){
  yield next;
  this.body = "should not enter here";
});


app.listen(3000);

我实际上可以改变我的路线:

router.get('/', function *(next){
  yield next;
  if(this.body !== "error")
    this.body = "should not enter here";
});

但是有更好的方法吗?还是我遗漏了什么?

这只是一个例子,实际上我的中间件可能会放置一个属性 在正文中(this.body.hasErrors = true),路线将从 那个。

再一次,我怎样才能在我的中间件中停止执行,这样我的路由就不会被执行?在 Express 中,我认为您可以做一个 response.end(虽然不确定)。

【问题讨论】:

    标签: node.js generator middleware koa


    【解决方案1】:

    中间件按照您将它们添加到应用程序的顺序执行。
    您可以选择屈服于下游中间件或提前发送响应(错误等)。 所以阻止中间件流的关键是不让步。

    app.use(function *(next){
      // yield to downstream middleware if desired
      if(doValidation(this)){
        yield next;
      }
      // or respond in this middleware 
      else{
        this.throw(403, 'Validation Error');
      }
    });
    
    app.use(function *(next){
      // this is added second so it is downstream to the first generator function
      // and can only reached if upstream middleware yields      
      this.body = 'Made it to the downstream middleware'
    });
    

    为清楚起见进行编辑:

    下面我已经修改了你原来的例子,让它按照我认为你想要的方式工作。

    var koa = require('koa');
    var router = require('koa-router')();
    var app = koa();
    
    // move route handlers below middleware
    //app.use(router.routes());
    
    // middleware
    app.use(function *(next){
      var valid = false;
      if (!valid){
        console.log('entered validation')
        this.body = "error"
        // return this.body; // how to stop the execution in here
      }
      else{
        yield next;
      }
    });
    
    // route
    router.get('/', function *(next){
      // based on your example I don't think you want to yield here
      // as this seems to be a returning middleware
      // yield next;
      this.body = "should not enter here";
    });
    
    // add routes here
    app.use(router.routes());
    
    app.listen(3000);
    

    【讨论】:

    • 嗨,詹姆斯,感谢您的回复。首先,我非常感谢您的博客帖子knowthen.com.. 它对我帮助很大...回到我的问题.. :).. 实际上我的中间件没有做任何收益.. 只有路线(向下游屈服).. 你知道如何做到这一点吗?或者我做错了 2 倍...
    • 嗨詹姆斯,谢谢......我的路线不应该有收益 - 这是我做错的事情......感谢您指出这一点......
    • @daxsorbito 几件事:总是返回的中间件,不应该像你提到的那样有产量,验证中间件应该有条件产量(你原来的例子没有这个)和你的顺序添加中间件很重要。您在验证中间件之前添加了返回中间件,因此流程从返回中间件开始,永远不会到达验证中间件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2016-12-25
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2022-11-10
    相关资源
    最近更新 更多