koa2入門--03.koa中間件以及中間件執行流程

//中間件:先訪問app的中間件的執行順序相似嵌套函數,由外到內,再由內到外
//應用級中間件
const koa = require('koa');
var router = require('koa-router')();
var app = new koa();

//匹配任意路由以前打印日期
app.use(async (ctx,next)=>{
    console.log(new Date());
    await next();
});
router.get('/',async (ctx)=>{
    ctx.body = '首頁';
});


//路由級中間件
//匹配到news後繼續向下匹配路由
router.get('/news',async (ctx,next)=>{
    console.log('這是一個新聞');
    await next();
});
router.get('/news',async (ctx)=>{
    ctx.body = '這是一個新聞';
});


//錯誤處理中間件
app.use(async (ctx,next)=>{
    console.log('這是一箇中間件01');
    next();//先處理中間節
    if(ctx.status == 404){
        ctx.status = 404;
        ctyx.body = '這是一個404頁面';
    }else{
        console.log(ctx.url);
    }
});


app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
相關文章
相關標籤/搜索