koa-router

子路由的简单实现

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’ }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值