Koa2:如何编写中间件链? [英] Koa2: how to write chain of middleware?

查看:106
本文介绍了Koa2:如何编写中间件链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在快递中,我们可以有一个中间件链,复制一个示例:

So in express, we can have a chain of middleware, copies an example:

middleware = function(req, res){
  res.send('GET request to homepage');
});

app.get('/', middleware, function (req, res) {
  res.send('GET request to homepage');
});

请问用koa2编写此代码的等效方法是什么? 我正在考虑将其用于路由,对于每个路由,我都希望有一个中间件来检查用户是否已经登录.

What's the equivalent way to write this in koa2 please ? I'm thinking of using it for the route, for each route i want to have a middleware to check if user is already logged in.

谢谢!

推荐答案

如果您只是想确保中间件软件为每条路由运行,您要做的就是在注册中间件之前您注册了路由中间件.

If you're simply interested in making sure a middlware runs for every route, all you have to do is register the middleware before you register your routing middelware.

app.use(middleware);

只要您在路由器使用"之前将其称为"",就会为每个请求调用它.只要确保您调用下一个函数即可.这就是您的中间件的样子:

As long as you call this before you 'use' your router, it will be called for every request. Just make sure you call the next function. This is how your middleware might look like:

function middleware(ctx, next) {

   // Authenticate user

   // Eventually call this
   return next();

}

这篇关于Koa2:如何编写中间件链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆