我决定按用途拆分我的路由器,所以它们看起来像这样:
路由器/homeRouter.ts
import * as Router from 'koa-router';
const router: Router = new Router();
router
.get('/', async (ctx, next) => {
ctx.body = 'hello world';
});
export = router;
路由器/userRouter.ts
import * as Router from 'koa-router';
import UserController = require('../controller/userController');
const router: Router = new Router(
{
prefix: 'users'
}
);
var userController = new UserController();
router
.post('/user/:email/:password', userController.signUp);
export = router;
有了这个,我的 app.ts 必须像这样一个一个地导入每个路由器:
应用程序.ts
import * as Koa from 'koa';
import * as homeRouter from './routers/homeRouter';
import * as userRouter from './routers/userRouter';
const app: Koa = new Koa();
app
.use(homeRouter.routes())
.use(homeRouter.allowedMethods());
app
.use(userRouter.routes())
.use(userRouter.allowedMethods());
app.listen(3000);
但我想要的是这样的:
应用程序.ts
import * as Koa from 'koa';
import * as routers from './routers';
const app: Koa = new Koa();
app
.use(routers.routes())
.use(routers.allowedMethods());
app.listen(3000);
我不知道如何导出路由器来实现这一点。任何人都可以帮忙吗?