egg.js之中间件

1.新建middleware文件
//options: 中间件的配置项,框架会将 app.config[${middlewareName}] 传递进来。
//app: 当前应用 Application 的实例。
module.exports = (options,app) => {

    //返回一个异步的方法
    return async function logData(ctx,next){
      console.log(123);
        await next();
    }
}

2.配置中间件,找到config中的  config.default.js 文件,配置下面内容,括号中为中间件名称

 config.middleware = ['logData'];

3. config.default.js 文件中给中间件传值,第一步中options参数将会接收此aaa参数

// add your middleware config here
  config.middleware = ['logData'];

  //给中间件传值
  config.logData ={
    aaa:'aaaaa'
  }

猜你喜欢

转载自www.cnblogs.com/hllzww/p/12981411.html