首页 > 其他 > 详细

koa-router学习笔记

时间:2019-12-10 18:54:18      阅读:77      评论:0      收藏:0      [点我收藏+]

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

koa-router学习笔记

原文:https://www.cnblogs.com/superlizhao/p/12018325.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!