路由
重要
koa
没有内封 router
,需要安装插件 koa-router
相关文档:@koa/router
bash
npm install @koa/router
npm install @types/koa__router -D
1
2
2
使用
typescript
import Koa from 'koa'
import Router from '@koa/router'
const app = new Koa()
const router = new Router()
// 注意这里使用的是 router.routers()
app.use(router.routes())
router.get('/', async (ctx: Koa.Context) => {
ctx.body = {
'path': ctx.request.path
}
})
app.listen(3000, '0.0.0.0', () => {
console.log('服务器启动成功')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
拆分
typescript
import Koa from 'koa'
import routers from './router'
const app = new Koa()
app.use(routers.routes()).use(routers.allowedMethods())
app.listen(3000, '0.0.0.0', () => {
console.log('服务器启动成功')
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
typescript
import Router from "@koa/router";
import publicRouter from "./publicRouter";
import adminRouter from './adminRouter'
const routers = new Router()
routers
.use('/public', publicRouter.routes(), publicRouter.allowedMethods())
.use(adminRouter.routes(), adminRouter.allowedMethods())
export default routers
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
typescript
import Router from "@koa/router";
import Koa from 'koa'
const publicRouter = new Router()
publicRouter
.get('/word-day', async function (ctx:Koa.Context){})
.get('/word-day/:id', async function (ctx:Koa.Context){})
export default publicRouter
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
typescript
import Router from '@koa/router'
import Koa from "koa";
const adminRouter = new Router().prefix('/admin') // 或 new Router({prefix: '/public'})
adminRouter
.post('/word-day', async function (ctx:Koa.Context){})
.put('/word-day', async function (ctx:Koa.Context){})
.delete('/word-day', async function (ctx:Koa.Context){})
export default adminRouter
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11