Koa2: how to write chain of middleware?

半世苍凉 提交于 2020-01-02 10:04:42

问题


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

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.

Thanks !


回答1:


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

}


来源:https://stackoverflow.com/questions/46187902/koa2-how-to-write-chain-of-middleware

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!