当前位置:网站首页>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 !
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 !
边栏推荐
- ~73 other text styles
- ~86m rabbit practice
- Resume of a microservice architecture teacher with 10 years of work experience
- Install docker under windows10 (through Oracle VM VirtualBox)
- High performance mysql (Third Edition) notes
- 7-12 inventory code base
- 汇编语言基础知识
- README. txt
- Shell_ 02_ Text three swordsman
- yum install xxx报错
猜你喜欢

~82 style of table

Resume of a microservice architecture teacher with 10 years of work experience

Some instructions on whether to call destructor when QT window closes and application stops

7-4 harmonic average

J'ai traversé le chemin le plus fou, le circuit cérébral d'un programmeur de saut d'octets

I'm "fixing movies" in ByteDance

~76 sprite map

「博士毕业一年,我拿下 ACL Best Paper」

The "advertising maniacs" in this group of programmers turned Tiktok advertisements into ar games

TCP的三次握手和四次挥手
随机推荐
Shell_ 03_ environment variable
"One year after graduation, I won ACL best paper"
~74 JD top navigation bar exercise
Idea resolving jar package conflicts
Eureka single machine construction
Shell_ 04_ Shell script
ByteDance technical Interviewer: what kind of candidate do I want to pick most
Error occurred during initialization of VM Could not reserve enough space for object heap
[graduation project] QT from introduction to practice: realize imitation of QQ communication, which is also the last blog post in school.
~81 long table
唯有学C不负众望 TOP3 Demo练习
Activiti directory (V) reject, restart and cancel process
Which is more important for programming, practice or theory [there are some things recently, I don't have time to write an article, so I'll post an article on hydrology, and I'll fill in later]
LeetCode 1640. Can I connect to form an array
字节跳动技术面试官现身说法:我最想pick什么样的候选人
Notes on how the network is connected
Continue and break jump out of multiple loops
MySQL date function
原型链继承
The "advertising maniacs" in this group of programmers turned Tiktok advertisements into ar games