如何不调用方法通过装饰器获取路由地址并注册Express路由?
解决方案
1. 修正GET装饰器,保留原方法并挂载路由信息
你当前的GET装饰器错误替换了原方法,导致业务逻辑丢失且无法正确挂载路由信息。修改为直接给原方法添加路由元数据:
export function GET(url: string) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { // 给原始方法挂载路由配置 const originalMethod = descriptor.value; originalMethod.routeMeta = { httpMethod: 'get', path: url }; return descriptor; } }
2. 修改Controller装饰器,遍历方法并注册到Express Router
在Controller装饰器中过滤构造函数,检查每个方法的路由元数据,拼接完整路径后注册到Router,同时绑定类实例保证this指向正确:
import express from 'express'; // 可根据项目结构调整Router实例的获取方式,比如传入或全局导出 const router = express.Router(); export function Controller(basePath: string) { return function(target: any) { const instance = new target(); // 获取原型上的所有方法名,排除构造函数 const methodNames = Object.getOwnPropertyNames(target.prototype).filter(name => name !== 'constructor'); methodNames.forEach(methodName => { const method = target.prototype[methodName]; // 检查方法是否有路由元数据 if (method.routeMeta) { const { httpMethod, path } = method.routeMeta; const fullPath = `${basePath}${path}`; // 绑定实例,确保方法内this指向类实例 router[httpMethod](fullPath, instance[methodName].bind(instance)); } }); } }
关键说明
- 不替换原方法:直接在原始方法上挂载元数据,既保留业务逻辑,又能在Controller装饰器中读取路由信息。
- 绑定类实例:Express调用路由处理函数时默认
this指向Router,必须用bind(instance)确保方法内的this指向UserController实例。 - 过滤构造函数:构造函数无需注册为路由,因此从方法列表中排除。
内容的提问来源于stack exchange,提问作者Magician
相关产品推荐
相关产品推荐

