Koa中间件

Koa中间件

十二月 12, 2018

一、什么是 Koa 中间件

通俗的讲中间件就是在匹配路由之前或者匹配路由完成后做的一系列的操作,我们就可以把它叫做中间件。
express 的中间件 (Middleware) 是一个函数,它可以访问请求对象 (request object / req) 与响应对象 (response object / res)。web 应用中处理“请求-响应循环”流程的中间件,一般被命名为 next 变量。Koa 的中间件和 express 有点类似。
中间件的功能包括:
1、执行任何代码。
2、修改请求和响应对象。
3、终结请求-响应循环。
4、调用堆栈中的下一个中间件。
中间件的标志是next,如果在 get、post 回调函数中没有 next 参数,那么匹配上第一个路由之后就不会往下匹配了。如果想继续往下匹配的话就需要写 next()

二、Koa 中可使用的中间件:

主要分为四种:应用级中间件、路由级中间件、错误处理中间件、第三方中间件

1. 应用级中间件

1
2
3
4
5
6
//匹配任何路由之前打印日期
app.use(async (ctx,next)=>{ //不写next路由就会终止

console.log(new Date());
await next(); //当前路由匹配完成以后继续向下匹配
})

2. 路由级中间件

1
2
3
4
5
6
7
8
9
10
// 匹配到news路由以后继续向下匹配
router.get('/news',async (ctx,next)=>{ //实现先打印后访问

console.log('这是一个新闻');
await next();
})
router.get('/news',async (ctx)=>{

ctx.body='这是一个新闻';
})

3. 错误处理中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
//输入路由
app.use(async (ctx,next)=>{

console.log('这是错误处理中间件'); //先打印这个
await next();

if(ctx.status==404){ //如果页面找不到
ctx.status = 404;
ctx.body="404 页面"
}else{
console.log(ctx.url); //如果页面找得到,先执行页面,最后打印其 url
}
})

4. 第三方中间件

1
2
3
4
5
6
7
8
const static = require('koa-static');
const staticPath = './static';
app.use(static(

path.join( __dirname, staticPath)
))
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

三、Koa 中间件的执行顺序

Koa 的中间件和 Express 不同,Koa 选择了洋葱模型。
8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//输入www.域名.com/news
app.use(async (ctx,next)=>{

console.log('1、第一个中间件');
await next();

console.log('5、匹配路由完成以后又会返回来执行中间件');
})

app.use(async (ctx,next)=>{

console.log('2、第二个中间件');
await next();

console.log('4、匹配路由完成以后又会返回来执行中间件');
})

router.get('/news',async (ctx)=>{

console.log('3、匹配到了news路由');
ctx.body='这是一个新闻';
})
//执行顺序12345