路由中间件:让中间件只在特定的路由中去使用。
demo让中间件只在首页起作用
//middleware/auth.js下定义中间件
module.exports = (option,app)=>{
return async function auth(ctx,next){
/* 实现中间件 */
console.log(new Date());
console.log(option.title)
await next()
}
}
//router.js 中使用中间件
module.exports = app => {
const { router, controller } = app;
//引入中间件
let auth = app.middleware.auth({title:"this is router.js"})
//在首页中使用中间件
router.get('/',auth, controller.home.index);
router.get('/news',controller.news.index);
};
Tips:不要在config/config.default.js中去配置中间件,不然它就是一个通用型的中间件