zoukankan      html  css  js  c++  java
  • nodejs+koa 后台框架结构、demo学习地址

    框架结构例子

    https://github.com/bayi-lzp/koa-template

    官网例子(有很多 示例)

    https://github.com/koajs/examples

    《Koa2进阶学习笔记》电子书

    https://github.com/chenshenhai/koa2-note

    实战项目1

    • Node.js + Koa2 + MySQL 开发的一套完整 RESTful API
    • Vue.js + element-ui 管理后台
    • SSR Nuxtjs 前台服务端渲染

    https://github.com/lfb/nodejs-koa-blog

    实战项目2

    https://gitee.com/caiheping/koa-template

    https://gitee.com/caiheping/vue-template

    项目的结构都可以借鉴。

    tip: 注意,不要把 static 中间件放到 Koa 的全局中间件上(如果对于每个请求都需要判断一次是不是静态资源,会影响 QPS),最好结合 koa-router 来处理,按需挂在,上代码。

    ctx.url = path.basename(ctx.url)
      await next()
    }, staticServer(resolve('./public'), {gzip: true}))

    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


    使用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

  • 相关阅读:
    道路和航线(最短路SPFA优化算法)
    走廊泼水节 (最大生成树)
    大数板子
    强连通分量
    path(CCPC网络赛)
    Plug It In!(网络流板子)
    链式前向星上DFS(Pants On Fire)
    手环定理
    (x+y)%p==b ;(x*y)%p==c; 知道b,c,求x,y;
    牛客多校第六场-H-Pair
  • 原文地址:https://www.cnblogs.com/jiayouba/p/15138447.html
Copyright © 2011-2022 走看看