当前位置:网站首页>koa中间件
koa中间件
2022-07-06 09:29:00 【社会你磊哥,命硬不弯腰】
中间件的工作原理
初始化koa实例后,我们会用use方法来加载中间件(middleware),会有一个数组来存储中间件,use调用顺序会决定中间件的执行顺序。
每个中间件都是一个函数(不是函数将报错),接收两个参数,第一个是ctx上下文对象,另一个是next函数(由koa-compose定义)
在建立好http服务器后,会调用koa-compose模块对middleware中间件数组进行处理。具体代码这里就不贴了,原理就是:会从middleware数组中取第一个函数开始执行**,中间件函数中调用next方法就会去取下一个中间件函数继续执行。每个中间件函数执行完毕后都会返回一个promise对象。**(ps:调用next方法并不是表示当前中间件函数执行完毕了,调用next之后仍可以继续执行其他代码)
koa中间件的工作原理类似于洋葱模型,先由外而内,在由内而外!在底下将会举一个代码中的例子!
应用级中间件&&错误级中间件
//应用级中间件,最先执行
app.use(async(ctx,next)=>{
console.log("我是应用级中间件1");
//应用级中间件匹配任何路由,如果不写next()方法,则不会继续向下匹配!
await next();
//错误级中间件,之所以写在这里,和洋葱模型有关系,所有的应用级中间件执行完,又会从后往前执行await next()方法后面的代码!
if(ctx.status==404){
ctx.status=404;
ctx.body='我是404界面,请求失败!'
}
})
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx, next) => {
console.log(1)
await next() // 这里得到的就是中间件2返回的promise对象
console.log(3)
})
app.use((ctx) => {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log(2)
resolve() //这里如果不写resolve,则代码会卡在这里!
}, 2000)
})
})
app.listen(3000) //输出结果是1 2 3
路由级中间件
router.get('/news', async (ctx,next) => {
console.log("这是没有返回数据的新闻中间件!"); //如果不写next()方法,则不会继续匹配下面的路由方法!
await next();
})
router.get('/news', async (ctx) => {
ctx.body = "这是新闻界面"
})
最后就是async和await的使用,了解await后面跟的对象是promise对象和普通函数的区别!
边栏推荐
- ~Introduction to form 80
- [unsolved] 7-15 shout mountain
- 搭建flutter环境入坑集合
- ~85 transition
- Gridhome, a static site generator that novices must know
- Spark independent cluster dynamic online and offline worker node
- Shell_ 01_ data processing
- Story of [Kun Jintong]: talk about Chinese character coding and common character sets
- 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]
- Introduction to microservices
猜你喜欢
~Introduction to form 80
One hundred questions of image processing (1-10)
MP4格式详解
JS encapsulates the method of array inversion -- Feng Hao's blog
7-4 harmonic average
The concept of spark independent cluster worker and executor
Solve the single thread scheduling problem of intel12 generation core CPU (II)
Simply try the new amp model of deepfacelab (deepfake)
I'm "fixing movies" in ByteDance
Ffmpeg command line use
随机推荐
Shell_ 06_ Judgment and circulation
这116名学生,用3天时间复刻了字节跳动内部真实技术项目
SQL quick start
Fdog series (I): think about it. It's better to write a chat software. Then start with the imitation QQ registration page.
LeetCode 1584. Minimum cost of connecting all points
我走过最迷的路,是字节跳动程序员的脑回路
Record the error reason: terminate called after throwing an instance
Error occurred during initialization of VM Could not reserve enough space for object heap
Fdog series (4): use the QT framework to imitate QQ to realize the login interface, interface chapter.
原型链继承
[unsolved]7-14 calculation diagram
MP4格式详解
LeetCode 1550. There are three consecutive arrays of odd numbers
Shell_ 02_ Text three swordsman
7-5 blessing arrived
登陆验证koa-passport中间件的简单使用
Chapter 5 yarn resource scheduler
Cmake error: could not create named generator visual studio 16 2019 solution
~68 Icon Font introduction
The 116 students spent three days reproducing the ByteDance internal real technology project