egg-middleware 中间件

 

Middleware 中间件

 Egg 的中间件形式和 Koa 的中间件形式是一样的,都是基于洋葱圈模型。每次我们编写一个中间件,就相当于在洋葱外面包了一层。

 

编写中间件


 

 

写法

我们先来通过编写一个简单的中间件,来看看中间件的写法。

 

// app/middleware/middlewareOne.js
module.exports = (options, app) => {
    return async function middlewareOne(ctx, next) {
        console.log("==request one==");

        console.log(ctx.url)

        if(ctx.url === '/'){
            await next();
        }

        console.log("==response one==");
    }
};

 

配置

// config/config.default.js
exports.middleware = ['middlewareOne']; // 数组的顺序为中间件执行的顺序

 

 

router 中使用中间件

以上方式配置的中间件是全局的,会处理每一次请求。 如果你只想针对单个路由生效,可以直接在 app/router.js 中实例化和挂载,如下:

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  const gzip = app.middleware.middlewareOne();
  router.get('/', gzip, controller.home.index);
  router.get('/zyu', controller.home.zyu);
  router.get('/test', controller.test.index);
};

 

posted @ 2018-12-14 11:52  橘子味儿的猫  阅读(3087)  评论(0编辑  收藏  举报