一、什么是 Koa 的中間件
通俗的講:中間件就是匹配路由之前或者匹配路由完成做的一系列的操作,我們就可以把它叫做中間件。
在 express 中間件(Middleware)是一個函數(shù),它可以訪問請求對象(request object (req)), 響應對象(response object (res)), 和 web 應用中處理請求-響應循環(huán)流程中的中間件,一般被命名為 next 的變量。在 Koa 中中間件和 express 有點類似
中間件的功能包括:
執(zhí)行任何代碼。
修改請求和響應對象。
終結(jié)請求-響應循環(huán)。
調(diào)用堆棧中的下一個中間件。
如果我的 get、post 回調(diào)函數(shù)中,沒有 next 參數(shù),那么就配了。如果想往下匹配的話,那么需要寫 next()
二、Koa 應用可使用如下幾種中間件:
應用級中間件
路由級中間件
錯誤處理中間件
第三方中間件
1.應用級中間件
//引入 koa模塊
var Koa=require('koa');
var router = require('koa-router')(); /*引入是實例化路由** 推薦*/
var app=new Koa();
//Koa中間件
//匹配任何路由 ,如果不寫next,這個路由被匹配到了就不會繼續(xù)向下匹配
/*
app.use(async (ctx)=>{
ctx.body='這是一個中間件';
})
* */
/*匹配路由之前打印日期*/
app.use(async (ctx,next)=>{
console.log(new Date());
await next(); /*當前路由匹配完成以后繼續(xù)向下匹配*/
})
router.get('/',async (ctx)=>{
ctx.body="首頁";
})
router.get('/news',async (ctx)=>{
ctx.body="新聞列表頁面";
})
router.get('/login',async (ctx)=>{
ctx.body="新聞列表頁面";
})
app.use(router.routes()); /*啟動路由*/
app.use(router.allowedMethods());
app.listen(3002);
2.路由級中間件
//引入 koa模塊
var Koa=require('koa');
var router = require('koa-router')(); /*引入是實例化路由** 推薦*/
var app=new Koa();
//Koa中間件
//匹配任何路由,如果不寫next,這個路由被匹配到了就不會繼續(xù)向下匹配
router.get('/',async (ctx)=>{
ctx.body="首頁";
})
// 匹配到news路由以后繼續(xù)向下匹配路由
router.get('/news',async (ctx,next)=>{
console.log('這是一個新聞1');
await next();
})
router.get('/news',async (ctx)=>{
ctx.body='這是一個新聞';
})
router.get('/login',async (ctx)=>{
ctx.body="新聞列表頁面";
})
app.use(router.routes()); /*啟動路由*/
app.use(router.allowedMethods());
app.listen(3002);
3.錯誤處理中間件
//引入 koa模塊
var Koa=require('koa');
var router = require('koa-router')(); /*引入是實例化路由** 推薦*/
var app=new Koa();
//Koa中間件
//匹配任何路由 ,如果不寫next,這個路由被匹配到了就不會繼續(xù)向下匹配
//www.域名.com/news
app.use(async (ctx,next)=>{
console.log('這是一個中間件01');
next();
if(ctx.status==404){ /*如果頁面找不到*/
ctx.status = 404;
ctx.body="這是一個 404 頁面"
}else{
console.log(ctx.url);
}
})
router.get('/',async (ctx)=>{
ctx.body="首頁";
})
router.get('/news',async (ctx)=>{
console.log('這是新聞2');
ctx.body='這是一個新聞';
})
router.get('/login',async (ctx)=>{
ctx.body="新聞列表頁面";
})
app.use(router.routes()); /*啟動路由*/
app.use(router.allowedMethods());
app.listen(3002);
4.中間件執(zhí)行流程:洋蔥圈
//引入 koa模塊
var Koa=require('koa');
var router = require('koa-router')(); /*引入是實例化路由** 推薦*/
var app=new Koa();
//Koa中間件
//匹配任何路由 ,如果不寫next,這個路由被匹配到了就不會繼續(xù)向下匹配
//www.域名.com/news
app.use(async (ctx,next)=>{
console.log('1、這是第一個中間件01');
await next();
console.log('5、匹配路由完成以后又會返回來執(zhí)行中間件');
})
app.use(async (ctx,next)=>{
console.log('2、這是第二個中間件02');
await next();
console.log('4、匹配路由完成以后又會返回來執(zhí)行中間件');
})
router.get('/',async (ctx)=>{
ctx.body="首頁";
})
router.get('/news',async (ctx)=>{
console.log('3、匹配到了news這個路由');
ctx.body='這是一個新聞';
})
app.use(router.routes()); /*啟動路由*/
app.use(router.allowedMethods());
app.listen(3002);