和express的中间件一个道理,多了 async和await 语法;
中间件代码
function pv(ctx) {
// 打印路径
global.console.log('pv'+ctx.path)
}
// 输出一个函数 在use方法里调用 ,最终返沪一个async函数
module.exports = function () {
// ctx 是综合的请求体可以用来添油加醋, next 是处理完毕 需要进入下一层的方法
return async function (ctx,next) {
// 入参调用
pv(ctx);
// 调用next 进入下一个 中间件 或者 处理主体
await next();
}
}
在主代码中 引用并使用
const pv = require('./middleware/pv')
app.use(pv())
打印结果为
pv/
<-- GET /
GET / - 668ms
--> GET / 200 681ms 185b
pv/stylesheets/style.css
<-- GET /stylesheets/style.css
--> GET /stylesheets/style.css 200 35ms 111b
中间件的执行顺序为 洋葱一样的
pv.js
function pv(ctx) {
// 打印路径
global.console.log('pv'+ctx.path)
}
// 输出一个函数 在use方法里调用 ,最终返沪一个async函数
module.exports = function () {
// ctx 是综合的请求体可以用来添油加醋, next 是处理完毕 需要进入下一层的方法
return async function (ctx,next) {
global.console.log('pv start')
// 入参调用
pv(ctx);
// 调用next 进入下一个 中间件 或者 处理主体
await next();
global.console.log('pv end')
}
}
pv2.js
function pv(ctx) {
// 打印路径
global.console.log('pv2')
}
// 输出一个函数 在use方法里调用 ,最终返沪一个async函数
module.exports = function () {
// ctx 是综合的请求体可以用来添油加醋, next 是处理完毕 需要进入下一层的方法
return async function (ctx,next) {
// 入参调用
global.console.log('pv2 start')
pv(ctx);
// 调用next 进入下一个 中间件 或者 处理主体
await next();
global.console.log('pv2 end')
}
}
打印结果为
pv start
pv/stylesheets/style.css
pv2 start
pv2
<-- GET /stylesheets/style.css
pv2 end
pv end
--> GET /stylesheets/style.css 200 20ms 111b
跟洋葱一样的结构