当前位置:网站首页>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对象和普通函数的区别!
边栏推荐
- 字节跳动多篇论文入选 CVPR 2021,精选干货都在这里了
- Fdog series (I): think about it. It's better to write a chat software. Then start with the imitation QQ registration page.
- 谢邀,人在工区,刚交代码,在下字节跳动实习生
- Error occurred during initialization of VM Could not reserve enough space for object heap
- Simply try the new amp model of deepfacelab (deepfake)
- TypeScript基本操作
- Story of [Kun Jintong]: talk about Chinese character coding and common character sets
- Gridhome, a static site generator that novices must know
- The most lost road I have ever walked through is the brain circuit of ByteDance programmers
- Shell_ 03_ environment variable
猜你喜欢
FLV格式详解
Shell_ 01_ data processing
~85 transition
字节跳动新程序员成长秘诀:那些闪闪发光的宝藏mentor们
~74 JD top navigation bar exercise
Some instructions on whether to call destructor when QT window closes and application stops
The QT program compiled on CentOS lacks a MySQL driven solution
ByteDance open source Gan model compression framework, saving up to 97.8% of computing power - iccv 2021
CMake速成
字节跳动开源GAN模型压缩框架,算力最高节省97.8%丨ICCV 2021
随机推荐
我走过最迷的路,是字节跳动程序员的脑回路
LeetCode 1550. There are three consecutive arrays of odd numbers
LeetCode 1551. Minimum operand to make all elements in the array equal
Fdog series (V): use QT to imitate QQ to realize login interface to main interface, function chapter.
字节跳动新程序员成长秘诀:那些闪闪发光的宝藏mentor们
7-4 harmonic average
Shell_ 03_ environment variable
Soft music -js find the number of times that character appears in the string - Feng Hao's blog
Fdog series (I): think about it. It's better to write a chat software. Then start with the imitation QQ registration page.
@RestController、@Controller
面试集锦库
LeetCode 1552. Magnetic force between two balls
Codeforces Round #771 (Div. 2)
Restful style interface design
Basic principles of video compression coding and audio compression coding
这116名学生,用3天时间复刻了字节跳动内部真实技术项目
Redis standalone startup
LeetCode 1557. The minimum number of points that can reach all points
DS18B20數字溫度計系統設計
字节跳动技术新人培训全记录:校招萌新成长指南