当前位置:网站首页>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 !
边栏推荐
- Alibaba cloud server builds SVN version Library
- Log4j2 major vulnerabilities and Solutions
- 谢邀,人在工区,刚交代码,在下字节跳动实习生
- [unsolved]7-14 calculation diagram
- 在 vi 编辑器中的命令模式下,删除当前光标处的字符使用 __ 命 令。
- "One year after graduation, I won ACL best paper"
- Saw local status change event StatusChangeEvent [timestamp=1644048792587, current=DOWN, previous=UP]
- 7-6 sum of combinatorial numbers
- Jedis
- redux使用说明
猜你喜欢
搭建flutter环境入坑集合
~69 other ways to use icon fonts
一个数10年工作经验的微服务架构老师的简历
The most lost road I have ever walked through is the brain circuit of ByteDance programmers
姚班智班齐上阵,竞赛高手聚一堂,这是什么神仙编程大赛?
算数运算指令
Error occurred during initialization of VM Could not reserve enough space for object heap
这群程序员中的「广告狂人」,把抖音广告做成了AR游戏
The QT program compiled on CentOS lacks a MySQL driven solution
Activiti目录(三)部署流程、发起流程
随机推荐
字节跳动春招攻略:学长学姐笔经面经,还有出题人「锦囊」
Only learning C can live up to expectations top5 S1E8 | S1E9: characters and strings & arithmetic operators
程序员定位解决问题方法论
Error occurred during initialization of VM Could not reserve enough space for object heap
Fdog series (VI): use QT to communicate between the client and the client through the server (less information, recommended Collection)
Resume of a microservice architecture teacher with 10 years of work experience
~77 linear gradient
~79 Movie card exercise
After the subscript is used to assign a value to the string type, the cout output variable is empty.
Design of DS18B20 digital thermometer system
~73 other text styles
~74 JD top navigation bar exercise
Redis standalone startup
字节跳动多篇论文入选 CVPR 2021,精选干货都在这里了
~81 long table
redux使用说明
MySQL string function
Idea resolving jar package conflicts
Shell_ 01_ data processing
Go language uses the thrift protocol to realize the client and service end reports not enough arguments in call to oprot Writemessagebegin error resolution