停止KOA中的中间件pipe道执行

我想问一下在KOA中是否有办法停止执行中间件pipe道?

在下面的例子中,我有一个中间件,可以validation某些东西。 当validation失败时,我如何重新编码中间件以停止执行?

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"; }); 

但有没有更好的办法? 或者我错过了什么?

这仅仅是一个例子,实际上我的中间件可能会把一个属性放在body(this.body.hasErrors = true)中,路由会从中读取。

再次,我怎么能阻止我的中间件执行,所以我的路线不会被执行? 在快递我想你可以做一个response.end(不知道这个虽然)。

中间件按照您将其添加到应用程序的顺序执行。
您可以select下游中间件或早期发送响应(错误等)。 所以阻止中间件stream程的关键就是不让步。

 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);