koa-router 使用

基础

  • koa-router 是一个class;
  • 支持 get|put|post|patch|delete|del;
  • all匹配所有的方法;
// 导入 koa, koa2.x 中,koa 是一个类,需要用大写开头
const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
const indexRouter = new Router()

indexRouter.get('/', (ctx) => {
  ctx.body = 'index page'
})

indexRouter.get('/user', (ctx) => {
  ctx.body = 'user page'
})

app
  .use(indexRouter.routes())
  .use(indexRouter.allowedMethods()) // 当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.


app.listen('3000', () => {
  console.log('running in the http://localhost:3000')
})

路由增加前缀

  • new Router()时,可以增加入参 prefix;
// 导入 koa, koa2.x 中,koa 是一个类,需要用大写开头
const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
const indexRouter = new Router({
  prefix: '/api' // 需要加 / 
})

indexRouter.get('/', (ctx) => {
  ctx.body = 'index page'
})

indexRouter.get('/user', (ctx) => {
  ctx.body = 'user page'
})

app
  .use(indexRouter.routes())
  .use(indexRouter.allowedMethods()) // 当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.

app.listen('3000', () => {
  console.log('running in the http://localhost:3000')
})

动态路由

  • :key 的形式,动态匹配路由;
// 导入 koa, koa2.x 中,koa 是一个类,需要用大写开头
const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
const indexRouter = new Router()

indexRouter.get('/', (ctx) => {
  ctx.body = 'index page'
})

indexRouter.get('/user', (ctx) => {
  ctx.body = 'user page'
})

indexRouter.get('/user/:id', (ctx) => {
  ctx.body = 'user detail page'
})

app
  .use(indexRouter.routes())
  .use(indexRouter.allowedMethods()) // 当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.

app.listen('3000', () => {
  console.log('running in the http://localhost:3000')
})

嵌套路由

// 导入 koa, koa2.x 中,koa 是一个类,需要用大写开头
const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
const homeRouter = new Router()
const billRouter = new Router()

billRouter.get('/bill', (ctx) => {
  ctx.body = 'bill page'
})

billRouter.get('/bill/detail', (ctx) => {
  ctx.body = 'bill detail page'
})

homeRouter.get('/home', (ctx) => {
  ctx.body = 'home page'
})

homeRouter.use('/home', billRouter.routes(), billRouter.allowedMethods())

app
  .use(homeRouter.routes())
  .use(homeRouter.allowedMethods()) // 当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.

app.listen('3000', () => {
  console.log('running in the http://localhost:3000')
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值