zenweb 控制器与路由
演示
简单使用
在 src/controller 目录下新建一个文件 simple.ts
import { Context, mapping } from 'zenweb';
export class Controller {
@mapping()
index(ctx: Context) {
return 'Hello zenweb';
}
@mapping()
path2(ctx: Context) {
return 'Hello path2';
}
@mapping({ path: '/p3' })
path3(ctx: Context) {
return 'Hello path3';
}
@mapping({ method: 'POST' })
post(ctx: Context) {
return 'Hello post';
}
}
:::tip 注意
控制器方法中 return 数据如果需要统一处理需要安装 @zenweb/result@^3.5.0 模块,否则 return 数据会被设置到 ctx.body 上
:::
使用中间件
import { Context, Next, mapping, controller } from 'zenweb';
function actionLog(ctx: Context, next: Next) {
console.log('actionLog middleware')
return next();
}
export class Controller {
@mapping({ middleware: actionLog })
simple() {
return 'simple';
}
}
@controller({
middleware: actionLog,
})
export class Controller2 {
@mapping()
simple() {
return 'simple';
}
}