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); };