1.定义一个中间件在应用中的基础使用

1.1定义中间件

  1. //app/middleware/auth.js
  2. module.exports = (option,app)=>{
  3. return async function auth(ctx,next){
  4. /* 实现中间件 */
  5. console.log(new Date());
  6. await next()
  7. }
  8. }

1.2配置中间件

  1. //config/config.default.js
  2. // 增加配置中间件
  3. config.middleware = ['auth'];

1.3给中间件传参

  1. // 增加配置中间件
  2. config.middleware = ['auth'];
  3. config.auth = {
  4. /* 传递给中间件的option */
  5. title:"this is middleware-param"
  6. }

使用

  1. //auth.js
  2. module.exports = (option,app)=>{
  3. return async function auth(ctx,next){
  4. /* 实现中间件的参数 */
  5. console.log(option.title)
  6. await next()
  7. }
  8. }