zoukankan      html  css  js  c++  java
  • 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:

    this is a get response!
    

    POST:

    this is a post response!
    

    这是最基本的路由配置,虽然所有的路由都可以通过这样的方式配,但是在实际项目中,这样的代码后期会极其难以维护,我们还有更优雅的方式去配置你的路由。

    配置路由层级

    router.prefix

    koa-router提供一种router.prefix方法,此方法对于某一个router来说,是一个全局配置,此router的所有路径都会自动被添加该前缀。

    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/get

    this is a get1 response!
    

    localhost:8000/get

    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:

    this is a get response from router.use!
    

    动态路由参数

    类似于vue-router,可以将参数直接以 /path/parma 的形式传递参数。
    路由的param参数通过ctx.params获取。

    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-bfd05f80c7c4

    {
        "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
    

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

  • 相关阅读:
    概率论与统计学---笔记
    实用概率论与数理统计学--笔记
    并发编程总结5-JUC-REENTRANTLOCK-3(非公平锁)
    并发编程总结4-JUC-REENTRANTLOCK-2(公平锁)
    并发编程总结3——JUC-LOCK-1
    DOCKER & SWARM1.2
    Docker
    hdfs命令
    并发编程总结2——java线程基础2
    并发编程总结1——java线程基础1
  • 原文地址:https://www.cnblogs.com/shenshangzz/p/9973397.html
Copyright © 2011-2022 走看看