koa中的中间件无论在哪里,都先执行,与代码前后顺序无关
举例:
应用级中间件:
app.use(async (ctx,next) => {
console.log(new Data());
await next(); //当前路由匹配完成以后继续向下匹配
})
router.get('/',async (ctx) => { //2018-11-29 14:36:07
ctx.body="首页";
})
router.get('/news',async (ctx) => { //2018-11-29 14:37:01
ctx.body="新闻页";
})
路由中间件:
router.get('/',async (ctx,next) => {
console.log('这是主页1');
await next();
})
router.get('/',async (ctx) => {
ctx.body="这是主页";
})
错误处理中间件:
访问http://www.xxx.com/news 输出新闻页
访问http://www.xxx.com/xxx 输出这是一个404页面
app.use(async (ctx,next) => {
console.log('这是一个中间件');
next();
if(ctx.status == 404){
ctx.status = 404;
ctx.body="这是一个404页面";
}else{
console.log(ctx.url);
}
})
router.get('/',async (ctx) => { //2018-11-29 14:36:07
ctx.body="首页";
})
router.get('/news',async (ctx) => { //2018-11-29 14:37:01
ctx.body="新闻页";
})
当访问http://www.xxx.com/xxx时,会经过中间件控制台打印出‘这是一个中间件’,
然后到路由中间件去匹配‘/xxx’,这时因为找不到这个路由会返回中间件继续向下执行,
输出‘这是一个404页面’
第三方中间件
指的就是koa-session、koa-jwt等