在路由中使用中间件
- 只有指定路由可以使用中间件,无需在config配置
- 只需在相关路由的js中引入中间件,给指定路由配置中间件,在第二个参数配置
具体步骤如下:
-
新建app/middleware/test.js
module.exports=(option,app)=>{ return async function auth(ctx,next){ console.log(option); console.log(new Date()); await next(); } }
-
router.js 挂载指定的中间件
module.exports = app => { const { router, controller } = app; // 路由中获取中间件 const testM = app.middleware.test({ title: 'this is test middle ware!' }); router.get('/', testM, controller.home.index); router.get('/news', controller.news.index); };
-
此处只在首页会输出中间件信息,在其他路由没有中间件信息,这样就实现了
框架默认中间件的配置
在eggjs中内置了bodyParser中间件,这时候我们可以在框架中配置东西,一般无需配置,没有太多意义
// 对post提交数据的限制
config.bodyParser = {
jsonLimit: '10mb' //Default is 1mb.
}
官方文档:https://eggjs.org/zh-cn/basics/middleware.html
在Eggjs中引入koa的中间件
1 ) 规范的 Koa 的中间件
-
规范的Koa中间件比如: koa-jsonp、koa-cors, 直接可以在Koa中
app.use('中间件')
的中间件 -
在 Egg.js 框架里面可以非常容易的引入 Koa 中间件生态, Koa中间件基本都可以在Eggjs中使用
-
使用 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));
-
在eggjs中,我们按照框架的规范来在应用中加载这个 Koa 的中间件:
// app/middleware/compress.js // koa-compress 暴露的接口(`(options) => middleware`)和框架对中间件要求一致 module.exports = require('koa-compress');
config.middleware = ['compress']; config.compress = { threshold: 1024 //它支持指定只有当 body 大于配置的 threshold 时才进行 gzip 压缩 };
-
以及koa-jsonp插件也可以同样应用
2 ) 非规范的 Koa 中间件
-
比如像是这类中间件, 有多个参数的中间件,就是很典型的非标准中间件,需要解决参数的问题
const Middleware = require('some-kind-mw'); app.use(Middleware(a, b))
-
这样解决:
// 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
:设置符合某些规则的请求不经过这个中间件。
-
举例:
// add your middleware config here 加入中间件名 config.middleware = [ 'printdatex', 'forbidip', 'auth', 'jsonp', 'compress' ]; // 给中间件传入参数 config.printdatex = { aaa: 'aaa', // 自定义的参数 ignore: '/news', // 通用配置 }; config.compress = { enable: false, // 这里关闭,这种配置叫做通用配置 match: 'news/', // 通用配置,匹配到的会执行中间件, 和ignore不能同时用 threshold: 1024, // 它支持指定只有当 body 大于配置的 threshold 时才进行 gzip 压缩 }; config.auth = { // 通用配置,使用match函数可以匹配多个 match(ctx) { // ctx 上下文 可以获取请求的地址 console.log(ctx.request.url); if (ctx.request.url === '/shop' || ctx.request.url === '/news') { return true; // 这类匹配 } return false; // 不匹配 } };