当前位置:网站首页>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对象和普通函数的区别!
边栏推荐
- 字节跳动海外技术团队再夺冠:高清视频编码已获17项第一
- 亮相Google I/O,字节跳动是这样应用Flutter的
- Fdog series (4): use the QT framework to imitate QQ to realize the login interface, interface chapter.
- LeetCode 1550. There are three consecutive arrays of odd numbers
- The 116 students spent three days reproducing the ByteDance internal real technology project
- ~87 animation
- Simply try the new amp model of deepfacelab (deepfake)
- [unsolved]7-14 calculation diagram
- Codeforces Global Round 19
- 我走过最迷的路,是字节跳动程序员的脑回路
猜你喜欢

Solr standalone installation

~85 transition

100张图训练1小时,照片风格随意变,文末有Demo试玩|SIGGRAPH 2021

Full record of ByteDance technology newcomer training: a guide to the new growth of school recruitment

Solr word segmentation analysis

Basic principles of video compression coding and audio compression coding

One hundred questions of image processing (1-10)

The QT program compiled on CentOS lacks a MySQL driven solution

Data config problem: the reference to entity 'useunicode' must end with ';' delimiter.

LeetCode 1584. Minimum cost of connecting all points
随机推荐
SQL quick start
LeetCode 1551. Minimum operand to make all elements in the array equal
~86m rabbit practice
Data config problem: the reference to entity 'useunicode' must end with ';' delimiter.
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]
字节跳动2022校招研发提前批宣讲会,同学们最关心的10个问题
How to generate six digit verification code
亮相Google I/O,字节跳动是这样应用Flutter的
7-7 ring the stupid bell
Conception du système de thermomètre numérique DS18B20
Codeforces Global Round 19
7-10 punch in strategy
~72 horizontal and vertical alignment of text
Use JQ to realize the reverse selection of all and no selection at all - Feng Hao's blog
7-6 sum of combinatorial numbers
~85 transition
DS18B20數字溫度計系統設計
~75 background
视频压缩编码和音频压缩编码基本原理
Fdog series (V): use QT to imitate QQ to realize login interface to main interface, function chapter.