egg.js 中间件的使用

1.路由中间件  就是任意路由都触发的中间件

config.default.js

  // 配置中间件
  config.middleware = ['auth'];


  //给中间件传参


  config.auth={

    title:'this is auth111'
  }

middleware auth.js

module.exports = (option, app) => {
    return async function auth(ctx, next) {
        console.log(option);
        //实现中间件的功能
        console.log(new Date());
        await next();
    }
}

2.给指定路由使用中间件  配置文件中不再配置中间件

路由中直接引用 调用

 //路由中获取中间件
  var auth=app.middleware.auth({title:'this is router.js  middleware'})
  router.get('/',auth, controller.home.index);  

3.使用koa 规范中间件 即 app.use(xxx({xxx}))形式调用   参数为对象

koa-compress   

const compress = require('koa-compress')
const Koa = require('koa')

const app = new Koa()
app.use(compress({
  filter (content_type) {
  	return /text/i.test(content_type)
  },
  threshold: 2048,
  gzip: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  deflate: {
    flush: require('zlib').constants.Z_SYNC_FLUSH,
  },
  br: false // disable brotli
}))

egg使用koa   middleware compress.js

module.exports=require('koa-compress');

参数到配置文件中添加

 config.middleware = ['forbidip','compress','kip'];
  config.compress={
    threshold: 1024 //它支持指定只有当 body 大于配置的 threshold 时才进行 gzip 压缩
  }

2.koa-ip

const app = new Koa()
app.use((ctx, next) => {
  ctx.request.ip = '127.0.0.1'
  return next()
})
app.use(ip({
  blacklist: ['127.0.0.*'],
  handler: async (ctx, next) => {
    ctx.status = 403
  }
}))

egg middleware kip.js

module.exports=require('koa-ip');

参数到配置文件中添加

  config.kip={
    blacklist: ['192.168.0.114','127.0.0.1'],
    handler: async (ctx, next) => {
      ctx.status = 403,
      await ctx.render('403')
    }
  }

炫酷的动态403模板 可在https://www.mk2048.com/免费下载模板

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>403禁止页面模板</title>


<style>
@import url("https://fonts.googleapis.com/css?family=Share+Tech+Mono|Montserrat:700");

* {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    box-sizing: border-box;
    color: inherit;
}

body {
    background-image: linear-gradient(120deg, #4f0088 0%, #000000 100%);
    height: 100vh;
}

h1 {
    font-size: 45vw;
    text-align: center;
    position: fixed;
    width: 100vw;
    z-index: 1;
    color: #ffffff26;
    text-shadow: 0 0 50px rgba(0, 0, 0, 0.07);
    top: 50%;
    -webkit-transform: translateY(-50%);
            transform: translateY(-50%);
    font-family: "Montserrat", monospace;
}

div {
    background: rgba(0, 0, 0, 0);
    width: 70vw;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
            transform: translateY(-50%);
    margin: 0 auto;
    padding: 30px 30px 10px;
    box-shadow: 0 0 150px -20px rgba(0, 0, 0, 0.5);
    z-index: 3;
}

P {
    font-family: "Share Tech Mono", monospace;
    color: #f5f5f5;
    margin: 0 0 20px;
    font-size: 17px;
    line-height: 1.2;
}

span {
    color: #f0c674;
}

i {
    color: #8abeb7;
}

div a {
    text-decoration: none;
}

b {
    color: #81a2be;
}

a.avatar {
    position: fixed;
    bottom: 15px;
    right: -100px;
    -webkit-animation: slide 0.5s 4.5s forwards;
            animation: slide 0.5s 4.5s forwards;
    display: block;
    z-index: 4
}

a.avatar img {
    border-radius: 100%;
    width: 44px;
    border: 2px solid white;
}

@-webkit-keyframes slide {
    from {
        right: -100px;
        -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
        opacity: 0;
    }
    to {
        right: 15px;
        -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
        opacity: 1;
    }
}

@keyframes slide {
    from {
        right: -100px;
        -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
        opacity: 0;
    }
    to {
        right: 15px;
        -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
        opacity: 1;
    }
}
</style>
</head>
<body>
<h1>403</h1>
<div><p>> <span>ERROR CODE</span>: "<i>HTTP 403 Forbidden</i>"</p>
<p>> <span>ERROR DESCRIPTION</span>: "<i>Access Denied. You Do Not Have The Permission To Access This Page On This Server</i>"</p>
<p>> <span>ERROR POSSIBLY CAUSED BY</span>: [<b>execute access forbidden, read access forbidden, write access forbidden, ssl required, ssl 128 required, ip address rejected, client certificate required, site access denied, too many users, invalid configuration, password change, mapper denied access, client certificate revoked, directory listing denied, client access licenses exceeded, client certificate is untrusted or invalid, client certificate has expired or is not yet valid, passport logon failed, source access denied, infinite depth is denied, too many requests from the same client ip</b>...]</p>
<p>> <span>SOME PAGES ON THIS SERVER THAT YOU DO HAVE PERMISSION TO ACCESS</span>: [<a href="/">Home Page</a>, <a href="/">About Us</a>, <a href="/">Contact Us</a>, <a href="/">Blog</a>...]</p><p>> <span>HAVE A NICE DAY SIR AXLEROD :-)</span></p>
</div>


<script>
var str = document.getElementsByTagName('div')[0].innerHTML.toString();
var i = 0;
document.getElementsByTagName('div')[0].innerHTML = "";

setTimeout(function() {
    var se = setInterval(function() {
        i++;
        document.getElementsByTagName('div')[0].innerHTML = str.slice(0, i) + "|";
        if (i == str.length) {
            clearInterval(se);
            document.getElementsByTagName('div')[0].innerHTML = str;
        }
    }, 10);
},0);
</script>

</body>
</html>

4.使用koa非规范中间件 

koa

  const Middleware = require('some-koa-middleware');
    app.use(Middleware(options.compiler,options.xxxx))

egg

const Middleware = require('some-koa-middleware');
module.exports=(option,app)=>{
    return Middleware(options.compiler,options.xxxx);
}

5.通用中间件  就是再中间件配置文件中添加属性方法 

  • enable:控制中间件是否开启。
  • match:设置只有符合某些规则的请求才会经过这个中间件。
  • ignore:设置符合某些规则的请求不经过这个中间件。match相反  只可定义其一
  config.kip={
    blacklist: ['192.168.0.114','127.0.0.1'],
    match:'/he',
    enable:true,
    match(ctx) {
      // 只有 ios 设备才开启
      const reg = /iphone|ipad|ipod/i;
      return reg.test(ctx.get('user-agent'));
    },
    handler: async (ctx, next) => {
      ctx.status = 403,
      await ctx.render('403')
    }
  }

比如指定中间件使用,一是可以直接使用调用方式  二 配置文件中watch下路由或者通过方法定义规则

注意  中间件命名 若是 user_auth.js  再配置文件或者js代码中必须写为userAuth

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值