koa-router学习笔记


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())
...


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM