1、 两种装饰器 get是方法装饰器 target对应的是相应类的原型prototype controller是类的装饰器 target对应的是构造函数 但是在两个装饰器中console.log(target)与console.log(target.prototype)打印出来的都为{}, 这也导致了
console.log(Reflect.getMetadata(‘path’, target, key))无法打印, 因为for循环中target.prototype为空对象不能遍历。
当运行不报错的情况,只需要在tsconfig.json文件中把"target": “es2016” 改为 “target” : "es5"就可以了
当然这两个配置是一定要打开的
“experimentalDecorators”: true,
“emitDecoratorMetadata”: true,
import 'reflect-metadata';
import { Request, Response } from 'express'
// import {controller, get} from './decorator'
interface BodyRequest extends Request {
body: {
[key: string] : string | undefined;
}
}
export function controller(target: any) {
console.log(target.prototype);
for (let key in target.prototype) {
console.log(Reflect.getMetadata('path', target.prototype, key));
}
}
export function get(path: string) {
return function(target:any, key: string) {
Reflect.defineMetadata('path', path, target, key);
console.log(target);
};
}
@controller
class LoginController {
@get('/login')
login () {
}
@get('/')
home(req: BodyRequest, res: Response) {
const isLogin = req.session ? req.session.login : undefined;
if (isLogin) {
res.send(`
<html>
<body>
<a href= '/logout'> 退出 </a>
<a href= '/getData'> 爬取信息 </a>
<a href= '/showData'> 展示爬取信息 </a>
</body>
</html>
`)
} else {
res.send(`
<html>
<body>
<form method = 'post' action = '/login'>
<input type= "password" name = "password"/>
<button> 登录 </button>
</form>
</body>
</html>
`)
}
}
}