koa2

发布时间 2023-12-30 16:03:05作者: 波波波维奇~
  • koa2 是什么

    koa2 是 nodejs web server 框架

    框架(frame)和库(lib)的区别:框架是唯一的,库是可以共存的,框架关注全流程(如 Vue、React等),库关注单个功能(如 lodash 等)

  • 使用 koa2 处理 http请求

    我们新增两个接口(获取评论列表和新增评论)

//路径:koa-demo/routes/comment.js

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

router.prefix('/comment')

//处理get请求,获取请求列表
router.get('/list', async (ctx, next) => {
    const queryObj = ctx.query;
    ctx.body = {
        errno: 0,
        data:[
            {id: 1, user: "zhangsan", content: "张三留的言"},
            {id: 2, user: "lisi", content: "李四留的言"},
            {id: 3, user: "wangwu", content: "王五留的言"},
            {id: 4, user: "zhaoliu", content: "赵六留的言"},
            {id: 5, user: "tianqi", content: "田七留的言"},
            {id: 6, user: "sunba", content: "孙八留的言"},
            {id: 7, user: "laojiu", content: "老九留的言"},
        ],
        msg: `这是查看留言列表接口!共有${queryObj.number}条留言`
    }
})

//处理post请求,新增留言
router.post('/create', async (ctx, next) => {
    const bodyObj = ctx.request.body;
    ctx.body = `这是新增留言接口!您的留言内容是:“${bodyObj.content}”`
})

module.exports = router

 

  同时需要修改 app.js ,新建路由并注册

// 路径:koa-demo/app.js

//新建路由
const index = require('./routes/index')
const users = require('./routes/users')
const comment = require('./routes/comment')

//注册路由 routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(comment.routes(),comment.allowedMethods())

 

  • koa2 中间件

    中间件是流程上独立的业务模块,可以扩展,可以插拔,类似工厂上的流水线

    koa2 中的所有业务代码都是中间件

    app.use() 是 koa 用来加载中间件的方法

    路由也是中间件,但对 url 规则做了限制,只有符合 url 规则的请求,才会进路由中间件

  • 使用 中间件模拟登录验证功能
// 登录校验中间件
// 只有 username 和 password 都符合的才能进行 http 请求
app.use(async (ctx, next) => { const queryObj = ctx.request.query; //登录失败 if(queryObj.username !== 'zhangsan' || queryObj.password !== '123456'){ ctx.body = { errno: 1, msg: "登录失败", }; return; } //登陆成功 await next(); })

 

  • koa2 洋葱圈模型

    中间件机制是 koa2 的精髓,每个中间件都是 async 函数,中间件的机制运行就像洋葱圈

  

    顺序是:进入A → 进入B → 进入C → 离开C → 离开B → 离开A