当前位置:网站首页>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 !
边栏推荐
- 唯有學C不負眾望 TOP5 S1E8|S1E9:字符和字符串&&算術運算符
- Activiti目录(一)重点介绍
- 7-6 sum of combinatorial numbers
- 这116名学生,用3天时间复刻了字节跳动内部真实技术项目
- 控制转移指令
- "One year after graduation, I won ACL best paper"
- QT system learning series: 1.2 style sheet sub control lookup
- ~78 radial gradient
- ~69 other ways to use icon fonts
- Fdog series (VI): use QT to communicate between the client and the client through the server (less information, recommended Collection)
猜你喜欢

The most lost road I have ever walked through is the brain circuit of ByteDance programmers

~74 JD top navigation bar exercise

ByteDance 2022 school recruitment R & D advance approval publicity meeting, students' top 10 issues

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

原型链继承

Thank you for your invitation. I'm in the work area. I just handed in the code. I'm an intern in the next ByteDance

MySQL date function

我走過最迷的路,是字節跳動程序員的腦回路

Record the error reason: terminate called after throwing an instance

7-5 blessing arrived
随机推荐
8086 CPU 内部结构
7-4 harmonic average
DOS 功能调用
Jedis
唯有学C不负众望 TOP3 Demo练习
Shell_ 07_ Functions and regular expressions
TypeScript基本操作
[graduation project] QT from introduction to practice: realize imitation of QQ communication, which is also the last blog post in school.
服务器端渲染(SSR)和客户端渲染(CSR)的区别
~76 sprite map
算数运算指令
The 116 students spent three days reproducing the ByteDance internal real technology project
Fdog series (I): think about it. It's better to write a chat software. Then start with the imitation QQ registration page.
Error: case label `15 'not within a switch statement
After the subscript is used to assign a value to the string type, the cout output variable is empty.
Shell_ 01_ data processing
Activit fragmented deadly pit
控制转移指令
这群程序员中的「广告狂人」,把抖音广告做成了AR游戏
Von Neumann architecture