中間件:匹配路由前,匹配路由完成作的一系列操做app
//middleware/printdate.jsasync
module.exports = (options,app) => { return async function printdate(ctx,next){ console.log(options); //打印參數 console.log(new Date()); //打印時間 await next() } }
//config/config.default.jsspa
config.middleware = ['printdate']; config.printdate = { aaa:"aaa" }
刷新頁面
code
//middleware/forbidip.js中間件
module.exports = (options,app) => { return async function forbidip(ctx,next){ var forbidips = options.forbidips; var clientIp = ctx.request.ip; var hasIp = forbidips.some(val => { if(val == clientIp){ return true; } }) if(hasIp){ ctx.status = 403; ctx.body = '你的ip已經被屏蔽'; }else{ await next() } } }
//config/config.default.jsblog
config.middleware = ['printdate','forbidip']; config.printdate = { aaa:"aaa" } config.forbidip = { forbidips:[ '127.0.0.1', '192.168.0.10' ] }
頁面效果ip