当前位置:网站首页>[Nodejs] 20. Koa2 onion ring model ----- code demonstration

[Nodejs] 20. Koa2 onion ring model ----- code demonstration

2022-07-06 12:22:00 weiweicn!

notes : Demo official website (https://koa.bootcss.com/) The code in
 Insert picture description here

  1. The code is as follows :
//  demonstration koa2  Onion ring model of middleware 

const Koa = require('koa');
const app = new Koa;

// logger ctx = req+res
app.use(async(ctx, next) => {
    
    await next();               //  Execute next Middleware 
    const rt = ctx.response.get('X-Response-Time')     // res Get time difference 
    console.log(`${
    ctx.method} ${
    ctx.url} - ${
    rt}`)
})

// x-response-time
app.use(async(ctx, next) => {
    
    const start = Date.now();
    await next();              //  Execute next Middleware 
    const ms = Date.now()- start;       //  Calculate the time difference 
    ctx.set('X-Response-Time', `${
    ms}ms`)       //  Record / Set the time difference 
})

// response
app.use(async(ctx, next) => {
    
    ctx.body = 'Hello world';
})


app.listen(3000);
console.log('koa2 Has started listening 3000 port ') 
  1. Enter access in browser :
     Insert picture description here

 Insert picture description here

原网站

版权声明
本文为[weiweicn!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131546231821.html