跟我一塊兒瞭解koa中間件
1、是 什麼是 Koa 的中間件
通俗的講: :中間件就是匹配路由以前或者匹配路由完成作的一系列的操做,咱們就能夠
把它叫作中間件。
在 在express件 中間件( (Middleware )是一個函數,它能夠訪問請求對象(request object (req)),
響應對象(response object (res)), 和 web 應用中處理請求-響應循環流程中的中間件,一
般被命名爲 next 的變量。在 Koa 中中間件和 express 有點相似。
中間件的功能包括:
執行任何代碼。
修改請求和響應對象。
終結請求-響應循環。
調用堆棧中的下一個中間件。
若是個人 get、post 回調函數中,沒有 next 參數,那麼就匹配上第一個路由,就不會往下匹
配了。若是想往下匹配的話,那麼須要寫 next()
2、Koa 應用可以使用以下幾種中間件:
應用級中間件
路由級中間件
錯誤處理中間件
第三方中間件
1.應用級中間件web
//app.js //在匹配路由以前,會打印出時間 //引入 koa模塊 var Koa=require('koa'); var router = require('koa-router')(); /*引入是實例化路由** 推薦*/ var app=new Koa(); //Koa中間件 //匹配任何路由 ,若是不寫next,這個路由被匹配到了就不會繼續向下匹配 // 匹配路由以前打印日期 app.use(async(ctx,next)=>{ console.log(new Date()) await next() }) 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(3004);
路由級中間件express
//app1.js //引入 koa模塊 var Koa=require('koa'); var router = require('koa-router')(); /*引入是實例化路由** 推薦*/ var app=new Koa(); //Koa中間件 //匹配任何路由 ,若是不寫next,這個路由被匹配到了就不會繼續向下匹配 router.get('/',async (ctx)=>{ ctx.body="首頁"; }) // 匹配到news路由之後繼續向下匹配路由 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);
效果圖
koa中的錯誤處理中間件app
//app2.js var Koa = require('koa') var router = require('koa-router')() var app = new Koa() 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(3003);
咱們看下效果,就知道這個錯誤處理中間件究竟是什麼問題了
koa
4.koa中間件的執行流程async
//app3.js //引入 koa模塊 var Koa=require('koa'); var router = require('koa-router')(); /*引入是實例化路由** 推薦*/ var app=new Koa(); //Koa中間件 //匹配任何路由 ,若是不寫next,這個路由被匹配到了就不會繼續向下匹配 //www.域名.com/news app.use(async (ctx,next)=>{ console.log('一、這是第一個中間件01'); await next(); console.log('五、匹配路由完成之後又會返回來執行中間件'); }) app.use(async (ctx,next)=>{ console.log('二、這是第二個中間件02'); await next(); console.log('四、匹配路由完成之後又會返回來執行中間件'); }) router.get('/',async (ctx)=>{ ctx.body="首頁"; }) router.get('/news',async (ctx)=>{ console.log('三、匹配到了news這個路由'); ctx.body='這是一個新聞'; }) app.use(router.routes()); /*啓動路由*/ app.use(router.allowedMethods()); app.listen(3004);