egg中间件

时间:2020-05-30
本文章向大家介绍egg中间件,主要包括egg中间件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

中间件:匹配路由前、匹配路由完成做的一系列的操作。 Egg 是基于 Koa 实现的,所以 Egg 的中间件形式和 Koa 的中间件形式是一样的,都是基于洋葱圈模型

Koa中的中间件:

    http://eggjs.org/zh-cn/intro/egg-and-koa.html#midlleware

Egg中的中间件:

    http://eggjs.org/zh-cn/basics/middleware.html








一般来说中间件也会有自己的配置。在框架中,一个完整的中间件是包含了配置处理的。我们约定一个中间件是一个放置在 app/middleware 目录下的单独文件,它需要 exports 一个普通的 function,接受两个参数:
    options: 中间件的配置项,框架会将 app.config[${middlewareName}] 传递进来。
    app: 当前应用 Application 的实例。

demo:

app/middleware文件下

创建中间件forbidip.js和printdate.js中间件:

module.exports = (options, app) => {
   
    //返回一个异步的方法
    return async function forbidIp(ctx,next){

            //要屏蔽的id : 1.从数据库获取     2、从参数传入
          
            var forbidips=options.forbidips;  

        //    console.log(forbidips);


            //获取客户端的ip

            var clientIp=ctx.request.ip;            
            //some和forEach相似
            var hasIp=forbidips.some(function(val){
                
                if(val==clientIp){

                    return true;
                }

            })

            if(hasIp){
                //屏蔽
                   ctx.status = 403;                
                   ctx.body='您的ip已经被屏蔽';

            }else{
                await next();

            }
  

           
    }

};
// module.exports = (options, app) => {
   
//     //返回一个异步的方法
//     return async function forbidIp(ctx,next){

//             //要屏蔽的id : 1.从数据库获取     2、从参数传入



//             /*要屏蔽的ip*/
//             var forbidip='127.0.0.1';

//             //获取客户端的ip

//             // console.log(ctx.request.ip)

//             if(ctx.request.ip==forbidip){

//                 ctx.status = 403;                
//                 ctx.body='您的ip已经被屏蔽';
               
//             }else{
//                 await next();
//             }
           
//     }

// };
/*
options: 中间件的配置项,框架会将 app.config[${middlewareName}] 传递进来。
app: 当前应用 Application 的实例。


配置中间件

*/

module.exports = (options, app) => {
   
    console.log(options);
    //返回一个异步的方法
    return async function printDate(ctx,next){


            console.log(new Date());

            await next();
    }

};

在config.defalt.js下

 // 增加配置中间件
  config.middleware = ['printdate','forbidip'];

  //给printdate中间件传入的参数
  config.printdate={

    aaa:'aaaaaa'
  }


  config.forbidip={

    forbidips:[
      '127.0.0.1',
      '192.168.0.195'
    ]
  }

在 router.js 路由中使用中间件

创建 middleware/auth.js

module.exports=(option,app)=>{
    return async function auth(ctx,next){
    console.log(option);
    console.log(new Date());
    await next(); }
}
2、router.js 挂载指定的中间件
module.exports = app => {
const { router, controller } = app;
//路由中获取中间件
const auth = app.middleware.auth({ attr: 'this is router.js middleware' }); router.get('/', auth,controller.home.index);
router.get('/news', controller.news.index);
router.get('/shop', controller.shop.index);
};

框架默认中间件的配置
config.bodyParser={
  jsonLimit: '10mb' //Default is 1mb.
}

Egg.js 中使用 koa 的中间件 (规范的 Koa 的中间件)

在 Egg.js 框架里面可以非常容易的引入 Koa 中间件生态。

使用 koa-compress 开启服务器 Gzip 压缩功能,以 koa-compress 为例,在 Koa 中使用的方 法:

const koa = require('koa');
const compress = require('koa-compress');
const app = koa();
const options = { threshold: 2048 }; app.use(compress(options));

按照规范来在应用中加载这个 Koa 的中间件:

module.exports = require('koa-compress');
config.middleware = ['compress'];
 config.compress = {
  threshold: 1024 //它支持指定只有当 body 大于配置的 threshold 时才进行 gzip 压缩 
};

Egg.js 中使用 koa 的中间件 (非规范的 Koa 中间件)

// config/config.default.js 
module.exports = {
    webpack: {
           compiler: {}, 
            others: {},
    },
 };
// app/middleware/webpack.js
const webpackMiddleware = require('some-koa-middleware');
module.exports = (options, app) => {
    return webpackMiddleware(options.compiler, options.others);
}    

Egg.js 中间件的通用配置

无论是应用层加载的中间件还是框架自带中间件,都支持几个通用的配置项:

enable:控制中间件是否开启。

match:设置只有符合某些规则的请求才会经过这个中间件。

ignore:设置符合某些规则的请求不经过这个中间件。

https://eggjs.org/zh-cn/basics/middleware.html


demo:

egg 中间件的基本配置

app/middleware/auth.js

module.exports=(option,app)=>{



    return async function auth(ctx,next){


        console.log(option);

        //实现中间件的功能

        console.log(new Date());


        await next();

    }

}

config/config.default.js

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

  //给中间件传参
  config.auth={
    title:'this is auth'
  }

路由中使用中间件

router.js中

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;

  //路由中获取中间件

  var auth=app.middleware.auth({title:'this is router.js  middleware'})

  router.get('/',auth, controller.home.index);  

};

egg中使用koa中间件插件

在app/middleware下

创建compress.js

//egg.js中使用koa-compress开启压缩



/*

egg.js中配置koa-compress模块:


1、安装 cnpm  install koa-compress --save
2、middleware文件夹下面新建一个compress.js

3、在jsonp.js中引入koa-compress 并且通过module.exports暴露
module.exports=require('koa-compress');

4、config.default.js中配置jsonp中间件   config.middleware = ['compress'];

*/


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




//非标准的中间件

/*
koa中的非标准中间件的配置

    const Middleware = require('some-koa-middleware');


    app.use(Middleware(options.compiler,options.xxxx))


egg.js中非标准的中间件配置:


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

}

*/

jsoup.js

//egg.js的中间件生态基于koa
/*

egg.js中配置koa-jsonp模块:


1、安装 cnpm  install koa-jsonp --save
2、middleware文件夹下面新建一个jsonp.js

3、在jsonp.js中引入koa-jsonp 并且通过module.exports暴露
module.exports=require('koa-jsonp');

4、config.default.js中配置jsonp中间件   config.middleware = ['jsonp'];

*/

var jsonp=require('koa-jsonp');

module.exports=jsonp;

在config.default.js配置中间件

// 配置中间件
  config.middleware = ['jsonp','compress'];
  config.compress = {
    threshold: 1024 //它支持指定只有当 body 大于配置的 threshold 时才进行 gzip 压缩
  };
  //框架中间件的默认配置
  config.bodyParser={
    jsonLimit: '10mb' //Default is 1mb.   
  }

egg中的通用设置

/ config.middleware = ['auth','jsonp','compress','adminAuth'];
  // 配置中间件
  config.middleware = ['auth','jsonp','compress'];

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

  //https://eggjs.org/zh-cn/basics/middleware.html
  config.auth = {
    // enable:false, 
    // match: '/news',
    // ignore:'/news',

    match(ctx){
      // ctx 上下文  可以获取请求的地址
      console.log(ctx.request.url);
      if(ctx.request.url=='/shop' || ctx.request.url=='/news'){
        return true;
      }
      return false;      
    },
    title:'this is  middleware'
  };

 来源:三明网站优化

原文地址:https://www.cnblogs.com/vwvwvwgwgvervae/p/12993936.html