什么是 Koa 的中间件web
通俗的讲:中间件就是匹配路由以前或者匹配路由完成作的一系列的操做,咱们就能够 把它叫作中间件。express
在express中间件(Middleware)是一个函数,它能够访问请求对象(requestobject(req)) , 响应对象(responseobject(res)), 和 web 应用中处理请求-响应循环流程中的中间件,一 般被命名为 next 的变量。app
在 Koa 中中间件和 express 有点相似。koa
中间件的功能包括:执行任何代码。 修改请求和响应对象。 终结请求-响应循环。 调用堆栈中的下一个中间件async
若是个人 get、post 回调函数中,没有 next 参数,那么就匹配上第一个路由,就不会往下匹 配了。若是想往下匹配的话,那么须要写 next()函数
Koa 应用可以使用的几种中间件post
应用级中间件 ,路由级中间件 ,错误处理中间件 ,第三方中间件ui
应用级中间件spa
好比下面在匹配任何路由以前都须要先验证一些用户是否有权限访问这个页面,这里demo只是打印一下当前时间code
const koa = require('koa') const router = require('koa-router')() // 引入和实例化路由 const app = new koa() // 建立koa实列 app.use(async (ctx, next) => { console.log(new Date()) // 运行后在匹配任何一个路由以前都会先执行一下这个中间件,无论这个路由存不存在 await next() // 当前路由匹配完成后继续向下匹配 }) // 配置路由 router.get('/', async (ctx, next) => { ctx.body="Hello koa"; }) router.get('/news', async (ctx, next) => { ctx.body='这是新闻页面' }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000,()=>{ console.log('starting at port 3000'); })
路由中间件
const koa = require('koa') const router = require('koa-router')() // 引入和实例化路由 const app = new koa() // 建立koa实列 // 配置路由 router.get('/', async (ctx, next) => { ctx.body="Hello koa"; }) // 匹配到news路由之后继续往下匹配路由 router.get('/news', async (ctx, next) => { console.log('这是新闻页面'); await next() // 若是没有这个next那么访问路由/news会找不到这个路由 }); router.get('/news', async (ctx) => { console.log(ctx.params); ctx.body='这是新闻页面' }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000,()=>{ console.log('starting at port 3000'); })
错误处理中间件
const koa = require('koa') const router = require('koa-router')() // 引入和实例化路由 const app = new koa() // 建立koa实列 app.use(async (ctx, next)=> { console.log('这是一个中间件') next(); console.log(ctx.status) if(ctx.status==404){ ctx.status = 404; ctx.body="这是一个 404 页面" } }) // 配置路由 router.get('/', async (ctx, next) => { ctx.body="Hello koa"; }) router.get('/news', async (ctx) => { console.log('这是新闻页面') ctx.body='这是新闻页面' }); app.use(router.routes()) app.use(router.allowedMethods()); app.listen(3000,()=>{ console.log('starting at port 3000'); })
Koa 中间件的执行顺序
Koa 的中间件和 Express 不一样,Koa 选择了洋葱圈模型。
当服务端接收到请求后,先执行app.use中间件中next()上面的代码,next()后会去匹配路由,若是匹配到,执行匹配到的那个路由里面的代码,而后在执行中间件中next()下面的代码
const koa = require('koa') const router = require('koa-router')() // 引入和实例化路由 const app = new koa() // 建立koa实列 //匹配任何路由 ,若是不写next,这个路由被匹配到了就不会继续向下匹配 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, next) => { ctx.body="Hello koa"; }) router.get('/news', async (ctx) => { console.log('三、匹配到了news这个路由') ctx.body='这是新闻页面' }); app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3000,()=>{ console.log('starting at port 3000') })
执行结果