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.不同级别代码顺序无影响,都是先执行应用级再路由级