gpt4 book ai didi

node.js - 在 KOA 中停止中间件管道执行

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:15 24 4
gpt4 key购买 nike

请问有没有办法停止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 is just an example, in reality my middleware might put a property in the body (this.body.hasErrors = true) and the route would read from that.

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

最佳答案

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

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

关于node.js - 在 KOA 中停止中间件管道执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30753991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com