eggjs业务中间件中无法获取ctx.params

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012769002/article/details/81369997

问题

由于路由中间件的加载顺序在业务中间件之后,所以在这里无法取到ctx.params

// app/middleware/test.js
module.exports = options => {
  return async function (ctx, next) {
    ctx.logger.info(ctx.params); // undefined
    await next();
  };
};

解决方案

  • 自行解析
  • 路由match少的情况下,将全局中间件改为路由中间件
const test = app.controller.middleware.test();
router.get('/api/users', test(), app.controller.user);
  • 先执行 next()
// app/middleware/test.js
module.exports = options => {
  return async function (ctx, next) {
    await next();
    ctx.logger.info(ctx.params); // 这里可以取到params
  };
};
  • 调整中间件的加载顺序
    • 这种方案对系统的影响较大,可能会存在其他的问题

综合来看,第一种方案的适用性更广,第二、三种方案在部分逻辑下应用可行,第四种方案需要做好充分的测试

猜你喜欢

转载自blog.csdn.net/u012769002/article/details/81369997
今日推荐