Koa中间件
一、什么是Koa的中间件
**通俗的讲:**中间件就是匹配路由之前或者匹配路由完成做的一系列的操作,我们就可以叫它叫做中间件。
中间件的功能包括:
- 执行任何代码。
- 修改请求和响应对象。
- 终结请求-响应循环。
- 调用堆栈中的下一个中间件。
如果我的get、post回调函数中,没有next参数,那么久匹配上第一个路由,就不会往下匹配了。如果想往下匹配的话,那么需要写next()
二、Koa应用可使用如下几种中间件
应用级中间件
路由级中间件
错误处理中间件
第三方中间件
const Koa=require('koa');
const router=require('koa-router')();
st app=new Koa();
app.use(async(ctx,next)=>{
console.log("1、这是第一个中间件01");
await next();
console.log(1);
})
app.use(async(ctx,next)=>{
console.log("2、这是第二个中间件02");
await next();
console.log("4、匹配路由完成以后又会返回来执行中间件");
})
router.get('/',async(ctx)=>{
ctx.body="首页";
})
router.get('/news',async(ctx)=>{
console.log("3、匹配到了news这个路由");
ctx.body='这是一个新闻'
})
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3001);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Qg9rxmaF-1612786063816)(C:\Users\练智磊\AppData\Roaming\Typora\typora-user-images\image-20210207164119108.png)]输出
app.listen(3001);
[外链图片转存中...(img-Qg9rxmaF-1612786063816)]输出