eggjs的中间件分为全局中间件和router中间件。
全局中间件用法:
// app/middleware/requestTime.js module.exports = () => { return async (ctx: any, next: any) => { ctx.requestBeginTime = +new Date(); await next(); }; }; //中间件写法一致,都是返回一个async函数,然后async函数的参数包括: ctx、next。
全局中间件调用和配置方法:
// app/config/config_base.js import { join } from ‘path‘; module.exports = { // 中间件 //可以在配文件中按顺序写需要调用的中间件,参考洋葱圈模型 middleware: [‘requestTime‘, ‘errorHandler‘, ‘koaStatic‘], //如果中间件需要参数可以在这里配置,比如: koaStatic: join(__dirname, ‘dist‘) };
router中间件
// app/middleware/headerParse.js module.exports = () => { return async (ctx: any, next: any) => { // 获取 params ,只能在router中才有这个数据,全局中间件是没有这个的 let activityId = ctx.params.activityId; const requestParams = { activityId }; ctx.request.requestParams = requestParams; await next(); }; };
router中间件调用:
// app/router.ts import { Application } from ‘egg‘; export default (app: Application) => { const { router, controller, middlewares, } = app; router.get(‘/promotion/babelpc/:activityId‘, middlewares.headerParser(), controller.activity.render); };
原文:https://www.cnblogs.com/hellolol/p/11507858.html