12. 项目框架搭建 - 12.5 路由设计

优质
小牛编辑
133浏览
2023-12-01

使用koa-router中间件

路由目录

  1. # ...
  2. └── server # 后端代码目录
  3. └── routers
  4. ├── admin.js # /admin/* 子路由
  5. ├── api.js # resetful /api/* 子路由
  6. ├── error.js # /error/* 子路由
  7. ├── home.js # 主页子路由
  8. ├── index.js # 子路由汇总文件
  9. └── work.js # /work/* 子路由
  10. # ...

子路由配置

resetful API 子路由

例如api子路由/user/getUserInfo.json,整合到主路由,加载到中间件后,请求的路径会是 http://www.example.com/api/user/getUserInfo.json

./demos/project/server/routers/api.js

  1. /**
  2. * restful api 子路由
  3. */
  4. const router = require('koa-router')()
  5. const userInfoController = require('./../controllers/user-info')
  6. const routers = router
  7. .get('/user/getUserInfo.json', userInfoController.getLoginUserInfo)
  8. .post('/user/signIn.json', userInfoController.signIn)
  9. .post('/user/signUp.json', userInfoController.signUp)
  10. module.exports = routers

子路由汇总

./demos/project/server/routers/index.js

  1. /**
  2. * 整合所有子路由
  3. */
  4. const router = require('koa-router')()
  5. const home = require('./home')
  6. const api = require('./api')
  7. const admin = require('./admin')
  8. const work = require('./work')
  9. const error = require('./error')
  10. router.use('/', home.routes(), home.allowedMethods())
  11. router.use('/api', api.routes(), api.allowedMethods())
  12. router.use('/admin', admin.routes(), admin.allowedMethods())
  13. router.use('/work', work.routes(), work.allowedMethods())
  14. router.use('/error', error.routes(), error.allowedMethods())
  15. module.exports = router

app.js加载路由中间件

./demos/project/server/app.js

  1. const routers = require('./routers/index')
  2. // 初始化路由中间件
  3. app.use(routers.routes()).use(routers.allowedMethods())