koa路由使用

其实,router这个是一个很重要的内容,用户进行url访问就可以更好的使用

不用router中间件

app.use(async (ctx,next)=>{
  if (ctx.path === '/') {
    ctx.body = 'we are at home!';
  } else {
    await next;
  }
})

app.use(async (ctx,next)=>{
  if (ctx.path === '/404') {
    ctx.body = 'page not found';
  } else {
    await next;
  }
})

中间件写法

const Koa = require('koa')
const fs = require('fs')
const app = new Koa()

const Router = require('koa-router')

let home = new Router()

// 子路由1
home.get('/', async ( ctx )=>{
  let html = `
    <ul>
      <li><a href="/page/helloworld">/page/helloworld</a></li>
      <li><a href="/page/404">/page/404</a></li>
    </ul>
  `
  ctx.body = html
})

// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
  ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
  ctx.body = 'helloworld page!'
})

// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())

// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000, () => {
  console.log('[demo] route-use-middleware is starting at port 3000')
})

koa-router相关API

router
  .get('/', async (ctx, next) => {
    ctx.body = 'Hello World!';
  })
  .post('/users', async (ctx, next) => {...})
  .put('/users/:id', async (ctx, next) => {...})
  .del('/users/:id', async (ctx, next) => {...})
  .all('/users/:id', async (ctx, next) => {...})

router.all()用于表示上述所有的动词方法

router.get('/', async (ctx,next) => {
  ctx.body = 'Hello World!';
});

上面代码中,router.get方法的第一个参数是根路径,第二个参数是对应的函数方法。

路由参数

我们可以通过ctx.params得到URL参数

router.get('/:category/:title', function (ctx, next) {
  console.log(ctx.params);
  // => { category: 'programming', title: 'how-to-node' }
});

这里有个中路由中间件汇集https://cnodejs.org/topic/57838dfaee5f048d54f90877

参考:

https://chenshenhai.github.io/koa2-note/note/route/koa-router.html

https://gaianote.github.io/2017/04/24/koa2%E5%AD%A6%E4%B9%A0%E7%B3%BB%E5%88%97%E6%95%99%E7%A8%8B3_%E8%B7%AF%E7%94%B1%E4%B8%8Ekoa-router/

https://github.com/minghe/koa-book/blob/master/start/router.md



转载:https://www.jianshu.com/p/0d59a4270997

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值