基础
koa-router
是一个class
;- 支持
get|put|post|patch|delete|del
; all
匹配所有的方法;
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())
app.listen('3000', () => {
console.log('running in the http://localhost:3000')
})
路由增加前缀
new Router()
时,可以增加入参 prefix
;
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())
app.listen('3000', () => {
console.log('running in the http://localhost:3000')
})
动态路由
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())
app.listen('3000', () => {
console.log('running in the http://localhost:3000')
})
嵌套路由
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())
app.listen('3000', () => {
console.log('running in the http://localhost:3000')
})