子路由的简单实现
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
// 子路由home
let home = new Router()
home.get('/', async ( ctx )=>{
let html = `
<ul>
<li><a href="/page/helloworld">/page/helloworld</a></li>
<li><a href="/page/abc">/page/abc</a></li>
</ul>
`
ctx.body = html
})
// 子路由page
let page = new Router()
page.get('/abc', async ( ctx )=>{
ctx.body = 'abc page!'
}).get('/helloworld', async ( ctx )=>{
ctx.body = 'helloworld page!'
})
// 将子路由添加到router路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
// 将router路由绑定到app
app.use(router.routes()).use(router.allowedMethods())
app.listen(3000, () => {
console.log('[demo] route-use-middleware is starting at port 3000')
})
1.引入koa-router=>Router,通过Router实例化home、page和router
2.实现两个子路由
3.将子路由添加到router路由
4.将router路由绑定到app
子路由模块化
目录
admin.js
// 1.引入koa-router
const Router = require('koa-router')
// 2.创建admin路由对象
let admin = new Router()
// 3.admin路由逻辑
admin.get('/show', async ctx => {
ctx.response.body = "admin"
})
module.exports = admin.routes()
company.js
// 1.引入koa-router
const Router = require('koa-router')
// 2.创建admin路由对象
let company = new Router()
// 3.admin路由逻辑
company.get('/show', async ctx => {
ctx.response.body = "company"
})
module.exports = company.routes()
分别在admin.js和company.js创建了路由
admin/show
company/show
user/index.js
const Router = require('koa-router')
let router = new Router()
router.use('/company',require('./company'))
router.use('/admin',require('./admin'))
module.exports = router.routes()
在user/index.js中把admin和company路由添加到router
app.js
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
//创建总路由
let router = new Router()
// 将子路由user添加到总路由上
router.use('/user',require('./router/user'))
// 将总路由绑定到app上
app.use(router.routes())
app.listen(3000, () => {
console.log('[demo] route-use-middleware is starting at port 3000')
})
在入口app.js中创建总路由并把usr路由添加到总路由上,把总路由绑定到app上
http://localhost:3000/user/admin/show
http://localhost:3000/user/company/show
动态路由
admin.js
// 1.引入koa-router
const Router = require('koa-router')
// 2.创建admin路由对象
let admin = new Router()
// 3.admin路由逻辑
admin.get('/show:aid', async ctx => {
// 获取动态路由的传值
console.log(ctx.params)
ctx.response.body = "admin"
})
module.exports = admin.routes()
http://localhost:3000/user/admin/show:abc
打印:{ aid: ‘abc’ }