路由中间件:让中间件只在特定的路由中去使用。

demo让中间件只在首页起作用

  1. //middleware/auth.js下定义中间件
  2. module.exports = (option,app)=>{
  3. return async function auth(ctx,next){
  4. /* 实现中间件 */
  5. console.log(new Date());
  6. console.log(option.title)
  7. await next()
  8. }
  9. }
  1. //router.js 中使用中间件
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. //引入中间件
  5. let auth = app.middleware.auth({title:"this is router.js"})
  6. //在首页中使用中间件
  7. router.get('/',auth, controller.home.index);
  8. router.get('/news',controller.news.index);
  9. };

Tips:不要在config/config.default.js中去配置中间件,不然它就是一个通用型的中间件