实现一个koa-logger中间件

//koa-logger.js
module.exports = async(ctx,next)=>{
    const start = new Date().getTime()
    // 中间件异步处理
    await next()
    const end = new Date().getTime()
    // 打印出耗时还有长度
    console.log(ctx.request.url,end-start,ctx.body.length)
}

在server.js中使用

//server.js
const Koa = require('koa')
const app = new Koa()
const koaLog = require('./koa-logger')
// app.use(async(ctx,next)=>{
//     ctx.body = 'hello imooc'
// })
// 运行结果
// 135642
function delay(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve()
        },1000)
    })
}
app.use(koaLog)
app.use(async(ctx,next)=>{
    ctx.body = '1'
    //下一个中间件
    // setTimeout(()=>{
    //     next()
    // },2000)
  
    await next()
    ctx.body = ctx.body + '2'
})
app.use(async(ctx,next)=>{
    ctx.body+= '3'
    //下一个中间件
    await next()
    ctx.body = ctx.body + '4'
})
app.use(async(ctx,next)=>{
    ctx.body += '5'
    await delay()
    //下一个中间件
    await next()
    ctx.body = ctx.body + '6'
})
//启动应用
app.listen('3000')

原文地址:https://www.cnblogs.com/smart-girl/p/11270848.html