什么是koa中间件,他们的执行顺序是什么样的?

koa中间件

koa中,中间件分为应用级和路由级

//应用级
app.use(async (ctx, next) => { //应用级中间件 ,先执行中间件,再匹配路由
  console.log("进入应用级中间件2");
  next()
  console.log("出应用级中间件2");
})
// 路由级
router.get("/", async (ctx,next) => { // 路由级中间件
  console.log('进入路游级');
  next()
  console.log('出路游级');
  
})

它们的执行顺序是怎样的?

const Koa = require("koa")
// const Router = require("koa-router") // 引入并且实例化路由对象
// const router = new Router()
const router = require("koa-router")()// 引入并且实例化路由对象
let app = new Koa()
// 中间件执行顺序:先应用级再路由级,同级代码顺序会影响,不同级先执行应用级
app.use(async (ctx,next)=>{ //应用级中间件 ,先执行中间件,再匹配路由
  console.log("进入应用级中间件1");
  next()
  if(ctx.status === 404){
    ctx.body = "这是404页面"
  }else{
    console.log('没出错最后打印的');
    
  }
  console.log("出应用级中间件1");
})
router.get("/", async (ctx,next) => { // 路由级中间件
  console.log('进入路游级');
  next()
  console.log('出路游级');  
})
  app.use(async (ctx, next) => { //应用级中间件 ,先执行中间件,再匹配路由
    console.log("进入应用级中间件2");
    next()
    console.log("出应用级中间件2");
  })

router.get("/",async (ctx)=>{
  ctx.body = "首页"
  console.log('进入首页页面');
  
})

router.get("/news", async (ctx) => {
  ctx.body = "新闻列表"
  console.log('进入news');
})

// router.get("/newsDetail/:id", async (ctx) => { // 动态路由
router.get("/newsDetail", async (ctx) => {

  //获取get传值
  const dataObj = ctx.query 
  const urlStr = ctx.url
  ctx.body = "新闻详情"
  console.log('进入newsDetail');
})
app.use(router.routes())

app.listen(3000)

以上代码执行后控制台输出
在这里插入图片描述
可以得出结论
koa中间件执行顺序为:
1.先应用级再路由级。
2.同级别的中间件,代码顺序会影响执行顺序。
3.不同级别代码顺序无影响,都是先执行应用级再路由级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值