狭义中间件,请求/拦截 最显著的特征是
app.use()
最简单的场景是 Koa.js 官方支持传输静态文件中间件的实现koa-logger
。
本节主要以官方的
koa-logger
中间件为参考,实现了一个最简单的koa-logger
实现,方便原理讲解和后续二次自定义优化开发。
https://github.com/chenshenhai/koajs-design-note/tree/master/demo/chapter-04-01
## 安装依赖npm i## 执行 demonpm run start## 最后启动chrome浏览器访问## http://127.0.0.1:3000/hello## http://127.0.0.1:3000/world## 控制台显示结果<-- GET /hello--> GET /hello<-- GET /world--> GET /world
const logger = async function(ctx, next) {let res = ctx.res;// 拦截操作请求 requestconsole.log(`<-- ${ctx.method} ${ctx.url}`);await next();// 拦截操作响应 requestres.on('finish', () => {console.log(`--> ${ctx.method} ${ctx.url}`);});};module.exports = logger
const Koa = require('koa');const logger = require('./index');const app = new Koa();app.use(logger);app.use(async(ctx, next) => {ctx.body = 'hello world';});app.listen(3000, () => {console.log('[demo] is starting at port 3000');});