当前位置:网站首页>Koa Middleware

Koa Middleware

2022-07-06 17:02:00 Society, you Lei brother, life is hard, don't bend down

How middleware works

initialization koa After the instance , We will use use Method to load middleware (middleware), There will be an array to store the middleware ,use The call order will determine the execution order of the middleware .
Every middleware is a function ( Not a function will report an error ), Receive two parameters , The first is ctx Context object , The other is next function ( from koa-compose Definition )
In the establishment of good http After the server , Would call koa-compose The module of middleware Middleware array for processing . The specific code is not posted here , The principle is : From middleware Take the first function in the array to start execution **, Call in the middleware function next Method will take the next middleware function and continue to execute . Each middleware function will return a promise object .**(ps: call next Method does not mean that the current middleware function has been executed , call next You can continue to execute other code after )

koa The working principle of middleware is similar to the onion model , From the outside to the inside , Inside out ! An example in the code will be given below !
 Insert picture description here

Application level middleware && Error level Middleware

// Application level middleware , The first to perform 
app.use(async(ctx,next)=>{
    
   console.log(" I am an application level middleware 1");
// Application level middleware matches any route , If you don't write next() Method , Will not continue to match downward !
  await next();
  // Error level Middleware , The reason it's written here , It has something to do with the onion model , All application level middleware has been executed , It will be executed from the back to the front await next() Method !
   if(ctx.status==404){
    
    ctx.status=404;
    ctx.body=' I am a 404 Interface , request was aborted !'
  }  
})
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx, next) => {
    
    console.log(1)
    await next() //  What you get here is middleware 2 Back to promise object 
    console.log(3)
})
app.use((ctx) => {
    
    return new Promise((resolve,reject) => {
    
        setTimeout(() => {
    
            console.log(2)
            resolve()  // If you don't write here resolve, Then the code will get stuck here !
        }, 2000)
    })
})
app.listen(3000)  // The output is 1 2 3

Routing level middleware

router.get('/news', async (ctx,next) => {
    
  console.log(" This is a news middleware that does not return data !");   // If you don't write next() Method , Will not continue to match the following routing methods !
  await next();
})
router.get('/news', async (ctx) => {
    
  ctx.body = " This is the news interface "
})

The last is async and await Use , understand await The following object is promise The difference between objects and ordinary functions !

原网站

版权声明
本文为[Society, you Lei brother, life is hard, don't bend down]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060920412577.html