Koa 是一个由 Express 原班人马打造的新的 web 框架,Koa 自身并没有绑缚任何中间件,只提供了应用(Application)、上下文(Context)、要求(Request)、相应(Response)四个模块。底本 Express 中的路由(Router)模块已被移除,改成经由历程中间件的体式格局完成。相比较 Express,Koa 能让使用者更大程度上构建个性化的应用。
1. 中间件简介
Koa 是一个中间件框架,自身没有绑缚任何中间件。自身支撑的功用并不多,功用都能够经由历程中间件拓展完成。经由历程增加差别的中间件,完成差别的需求,从而构建一个 Koa 应用。
Koa 的中间件就是函数,可所以 async 函数,或是平常函数,以下是官网的示例:
// async 函数
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
// 平常函数
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
中间件能够经由历程官方保护的堆栈查找猎取,也能够依据需求编写属于本身的中间件。
2. 中间件道理
2.1 示例
下面是一个的 Koa 应用,简朴演示了中间件的实行递次:
const Koa = require('Koa');
const app = new Koa();
// 最外层的中间件
app.use(async (ctx, next) => {
await console.log(`第 1 个实行`);
await next();
await console.log(`第 8 个实行`);
});
// 第二层中间件
app.use(async (ctx, next) => {
await console.log(`第 2 个实行`);
await console.log(`第 3 个实行`);
await next();
await console.log(`第 6 个实行`);
await console.log(`第 7 个实行`);
});
// 最里层的中间件
app.use(async (ctx, next) => {
await console.log(`第 4 个实行`);
ctx.body = "Hello world.";
await console.log(`第 5 个实行`);
});
app.listen(3000, () => {
console.log(`Server port is 3000.`);
})
2.2 道理
从上面的示例中能够看出,中间件的实行递次并非从头至尾,而是类似于前端的事宜流。事宜流是先举行事宜捕捉,抵达目的,然后举行事宜冒泡。中间件的完成历程也是一样的,先从最表面的中间件最先实行,next()
后进入下一个中间件,一起实行到最内里的中间件,然后再从最内里的中间件最先往外实行。
Koa 中间件采纳的是洋葱圈模子,每次实行下一个中间件传入两个参数 ctx 和 next,参数 ctx 是由 koa 传入的封装了 request 和 response 的变量,能够经由历程它接见 request 和 response,next 就是进入下一个要实行的中间件。
3. 编写属于本身的中间件
3.1 token 考证的 middleware
前后端星散开辟,我们常采纳 JWT 来举行身份考证,个中 token 平常放在 HTTP 要求中的 Header Authorization 字段中,每次要求后端都要举行校验,如 Java 的 Spring 框架能够在过滤器中对 token 举行一致考证,而 Koa 则经由历程编写中间件来完成 token 考证。
// token.js
// token 中间件
module.exports = (options) => async (ctx, next) {
try {
// 猎取 token
const token = ctx.header.authorization
if (token) {
try {
// verify 函数考证 token,并猎取用户相干信息
await verify(token)
} catch (err) {
console.log(err)
}
}
// 进入下一个中间件
await next()
} catch (err) {
console.log(err)
}
}
// app.js
// 引入 token 中间件
const Koa = require('Koa');
const app = new Koa();
const token = require('./token')
app.use(token())
app.listen(3000, () => {
console.log(`Server port is 3000.`);
})
3.2 log 的 middleware
日记模块也是线上不可缺乏的一部分,完美的日记体系能够协助我们迅速地排查出线上的题目。经由历程 Koa 中间件,我们能够完成属于本身的日记模块
// logger.js
// logger 中间件
const fs = require('fs')
module.exports = (options) => async (ctx, next) => {
const startTime = Date.now()
const requestTime = new Date()
await next()
const ms = Date.now() - startTime;
let logout = `${ctx.request.ip} -- ${requestTime} -- ${ctx.method} -- ${ctx.url} -- ${ms}ms`;
// 输出日记文件
fs.appendFileSync('./log.txt', logout + '\n')
}
// app.js
// 引入 logger 中间件
const Koa = require('Koa');
const app = new Koa();
const logger = require('./logger')
app.use(logger())
app.listen(3000, () => {
console.log(`Server port is 3000.`);
})
能够连系 log4js 等包来纪录更细致的日记
4. 总结
至此,我们已相识中间件的道理,以及怎样完成一个本身的中间件。
中间件的代码一般比较简朴,我们能够经由历程浏览官方保护的堆栈中优异中间件的源码,来加深对中间件的明白和应用。
- 本文首发于民众号,更多内容迎接关注我的民众号:阿夸座谈