Koa

2022-02-27  本文已影响0人  kzc爱吃梨

Koa对比Express

编程模型不同

对语言特性的使用不同

示例代码
记录返回hello world的总耗时

import Koa from 'koa'

const app = new Koa()

app.use(async (ctx, next) => {
    //  空
    await next();
    const time = ctx.response.get('X-Response-Time');  //  读取response header
    console.log(`${ctx.url} - ${time}`);
});

app.use(async (ctx, next) => {
    const start = Date.now();  //  记录开始时间
    await next();
    const time = Date.now() - start;  //  记录结束时间 - start = 总耗时
    ctx.set('X-Response-Time', `${time}ms`);  //  写到response header里
});

app.use(async ctx => {
    ctx.body = 'Hello World';
    // 最后一个中间件可以不写 await next()
});

app.listen(3000, ()=> {
    console.log('listen 3000')
})
运行顺序

await next()是什么意思

释义

app.use(async(ctx,next)=> {
    const start = Date.now();
    await next();  // 等待 下一个中间件()
    const time = Date.now() - start;
    ctx.set('X-Response-Time',`${time}ms`)
})

await next()改写

改写成Promise 写法

app.use(async (ctx, next) => {
    const start = Date.now();
    return next().then(() => {
        const time = Date.now() - start;
        ctx.set('X-Response-Time', `${time}ms`)
    })
})
app.xxx
文档在此 ctx.xxx
文档在此 ctx.request.xxx
文档在此 ctx.response.xxx
文档在此
上一篇 下一篇

猜你喜欢

热点阅读