Koa2學習(六)使用koa-router

Koa2學習(六)使用koa-router

配置簡單路由

  1. 引入中間件
  2. 配置須要的路由
  3. 經過app.use註冊路由
const Koa = require('koa')
const app = new Koa()
// 引入koa-router並對其實例化
const router = require('koa-router')()
// 配置get路由
router.get('/get', function (ctx, next) {
  ctx.body = 'this is a get response!'
})
// 配置post路由
router.post('/post', function (ctx, next) {
  ctx.body = 'this is a post response!'
})
// 註冊路由
app.use(router.routes(), router.allowedMethods())

app.listen(8000)

module.exports = app

請求後咱們能夠看到結果:
GET:javascript

this is a get response!

POST:vue

this is a post response!

這是最基本的路由配置,雖然全部的路由均可以經過這樣的方式配,可是在實際項目中,這樣的代碼後期會極其難以維護,咱們還有更優雅的方式去配置你的路由。java

配置路由層級

router.prefix

koa-router提供一種router.prefix方法,此方法對於某一個router來講,是一個全局配置,此router的全部路徑都會自動被添加該前綴。node

const Koa = require('koa')
const app = new Koa()
// 引入koa-router
const router = require('koa-router')
// 這兩行代碼等同於 const router1 = require('koa-router')()
const router1 = new router()
// 爲router1配置路由前綴
router1.prefix('/pre')
router1.get('/get', function (ctx, next) {
  ctx.body = 'this is a get1 response!'
})
// router2不配置路由前綴
const router2 = new router()
router2.get('/get', function (ctx, next) {
  ctx.body = 'this is a get2 response!'
})
// 註冊路由
app.use(router1.routes(), router1.allowedMethods())
app.use(router2.routes(), router2.allowedMethods())

app.listen(8000)

module.exports = app

咱們用瀏覽器訪問,發現get1的路由是/pre/get1,get2的路由是/get2:
localhost:8000/pre/getvue-router

this is a get1 response!

localhost:8000/getjson

this is a get2 response!

router.use

使用router.use方法,一樣的可以爲路由分層,而且不會由於忽略了prefix的全局配置形成一些沒必要要的失誤,
推薦使用這一種方法爲路由分層瀏覽器

const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')
// 定義子路由
const router_children = new router()
router_children.get('/get', function (ctx, next) {
  ctx.body = 'this is a get response from router.use!'
})
// 根路由
const router_root = new router()
// 在根路由中註冊子路由
router_root.use('/root', router_children.routes(), router_children.allowedMethods())
// 在app中註冊根路由
app.use(router_root.routes(), router_root.allowedMethods())
app.listen(8000)

module.exports = app

瀏覽器訪問localhost:8000/root/get:bash

this is a get response from router.use!

動態路由參數

相似於vue-router,能夠將參數直接以 /path/parma 的形式傳遞參數。
路由的param參數經過ctx.params獲取。app

const Koa = require('koa')
const app = new Koa()
const koa_router = require('koa-router')
const router = new koa_router()
router.get('/:category/:page/:id', function (ctx, next) {
  ctx.body = ctx.params
})
app.use(router.routes(), router.allowedMethods())
app.listen(8000)

module.exports = app

瀏覽器訪問localhost:8000/story/99/195c6f5b-2f71-4412-9634-bfd05f80c7c4koa

{
    "category": "story",
    "page": "99",
    "id": "195c6f5b-2f71-4412-9634-bfd05f80c7c4"
}

分割路由文件

當咱們的項目越作越大時,可能最終會有成百上千個路由,若是這些路由所有寫在一個文件下面,對後期的維護將是一個極大的考驗。
所以爲了讓咱們的代碼具有高可維護性,可拓展性,咱們最好對路由進行切割並分層,咱們藉助node.jsfs模塊對文件操做可以很輕易的實現路由切割。
若是你對fs模塊還不太瞭解,請先自行學習此模塊。

app.js:

const Koa = require('koa')
const app = new Koa()
const routes = require('./routes')
app.use(routes.routes(), routes.allowedMethods())
app.listen(8000)

module.exports = app

此段用來引入並註冊routes文件夾下的index.js文件。

routes/index.js:

const router = require('koa-router')()
const fs = require('fs')
const path = require('path')

const files = fs.readdirSync(__dirname)
files
    .filter(file => ~file.search(/^[^\.].*\.js$/))
    .forEach(file => {
        const file_name = file.substr(0, file.length - 3);
        const file_entity = require(path.join(__dirname, file));
        if (file_name !== 'index') {
            router.use(`/${file_name}`, file_entity.routes(), file_entity.allowedMethods())
        }
    })

module.exports = router

這一段代碼特別關鍵,用來引入並註冊全部同級目錄下的js文件(此目錄下的js文件都是路由文件),併爲他們配上以文件名命名的層級前綴。

routes/demo.js:

const router = require('koa-router')()

router.get('/', function (ctx, next) {
  ctx.body = 'demo'
})

router.get('/child', function (ctx, next) {
  ctx.body = 'demo child'
})

module.exports = router

這個就是業務的示例文件,沒什麼特別的。須要新增路由只須要新增此類文件便可。

經過瀏覽器進行訪問測試
localhost:8000/demo/child

demo child

localhost:8000/demo

demo

好了,路由已經被成功分割。

相關文章
相關標籤/搜索