如何在路由器路由中添加异步中间件



我有一个express路由器,我正在为它配置一些路由,我传递一个验证器的数据和一个处理程序,但验证器必须与一些承诺工作,所以我需要放置一个await,我写的代码看起来像这样:

constructor() {
this.router = express.Router();
this.router.use(express.json());
this.router.use(express.text({ type: ['text/plain', 'text/html'] }));
}
async addCreateTaskRoute(validator, handler) {
if (!handler) {
throw Error('cannot add empty handler');
}
this.router.post('/tasks', await validator, handler);
return this;
}

你觉得这个解决方案合适吗?还有其他选择吗?这个包含的项目是一个中间件,验证器和处理程序来自其他模块,它们的类型是express RequestHandler

您的validator应该在成功验证后异步调用next(),这将调用下一个中间件,即handler。验证不成功后,返回一个错误,并且不调用next(),因此不处理进一步的中间件。

async function validator(req, res, next) {
var valid = await validationResult(...);
if (valid) next();
else res.status(400).end("Error message");
}
this.router.post("/tasks", validator, handler);

最新更新