問題
由於路由中間件的加載順序在業務中間件之後,所以在這裏無法取到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
};
};
- 調整中間件的加載順序
- 這種方案對系統的影響較大,可能會存在其他的問題
綜合來看,第一種方案的適用性更廣,第二、三種方案在部分邏輯下應用可行,第四種方案需要做好充分的測試