koa2中间件
# koa2 中间件
提示
本教程是在koa中文网 (opens new window)文档的学习和总结
# 一、什么是Koa的中间件
通俗的讲:中间件就是匹配路由之前或者匹配路由完成做的一系列的操作,我们就可以把它叫做中间件。
在express中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处理请求-响应循环流程中的中间件,一般被命名为 next 的变量。在Koa中中间件和express有点类似。
中间件的功能包括:
执行任何代码。 修改请求和响应对象。 终结请求-响应循环。 调用堆栈中的下一个中间件。
如果我的get、post回调函数中,没有next参数,那么就匹配上第一个路由,就不会往下匹配了。如果想往下匹配的话,那么需要写next()
# 二、为什么使用中间件
- 拆分业务模块,使代码清晰
- 统一使用中间件,使得各业务代码都规范标准
- 扩展性好,易添加、易删除.
# 三、Koa应用可使用如下几种中间件:
- 应用级中间件
- 路由级中间件
- 错误处理中间件
- 第三方中间件
# 1.应用级中间件
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
app.use(async (ctx,next)=>{
	console.log(new Date());
	await next();
})
router.get('/', function (ctx, next) {
	ctx.body="Hello koa";
})
router.get('/news',(ctx,next)=>{
	ctx.body="新闻页面"
});
app.use(router.routes()); //作用:启动路由
app.use(router.allowedMethods()); //作用: 当请求出错时的处理逻辑
app.listen(3000,()=>{
	console.log('starting at port 3000');
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 2、路由中间件
router.get('/', async(ctx, next)=>{
	console.log(1)
	next()
})
router.get('/', function (ctx) {
	ctx.body="Hello koa";
})
1
2
3
4
5
6
7
2
3
4
5
6
7
# 3、错误处理中间件
app.use(async (ctx,next)=> {
	next();
	if(ctx.status==404){
	ctx.status = 404;
	ctx.body="这是一个404页面"
}
});
1
2
3
4
5
6
7
2
3
4
5
6
7
# 4、第三方中间件
const static = require('koa-static'); 
	const staticPath = './static'; 
	app.use(static(
	path.join( __dirname, staticPath)
)) 
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 四、koa2业务代码都是中间件
- app.use(..)都属于中间件, 所有的请求都会经过中间件
- 路由也是中间件,只有满足路由规则才会进入这个中间件
# 五、中间件规则
不管是什么类型的中间件(路由的或者自定义的),它都是一个async函数。async函数的第一个参数是ctx,第二个参数是next。
# 六、模拟登陆 中间件
app.js中添加中间件逻辑代码
app.use(async(ctx, next) => {
        const query = ctx.query
        if (query.user === 'zhangsan') {
            // 模拟登陆成功
            await next() // 执行下一个重甲件
        } else {
            // 登陆失败
            ctx.body = "请登录"
        }
    })
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 七、Koa中间件的执行顺序
Koa 的中间件和 Express 不同,Koa 选择了洋葱圈模型。

上次更新: 2023/09/05 17:45:42
