koa-router 是koa框架的一个路由处理级别的中间件。
目录结构
├── app.js
├── middleware
│ ├── m1.js
│ └── m2.js
├── package-lock.json
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.ejs
└── index.ejs
定义router
routes/index.js
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
//渲染views下的index.ejs
await ctx.render('index', {
title: 'Hello Koa 23s!'
})
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
module.exports = router
routes/users.js
const router = require('koa-router')()
//前缀
router.prefix('/users')
router.get('/', function (ctx, next) {
ctx.body = 'this is a users response!'
})
router.get('/bar', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
module.exports = router
app.js里引入
...
const index = require('./routes/index')
const users = require('./routes/users')
...
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
...