Koa简介、工作原理

官网:https://koajs.com/

核心概念:应用、请求、上下文(流水线)、响应

特点:轻量、简洁 , 支持async/await

  • 用同步的写法执行异步方法
  • 没有任何预置中间件
  • 最主要是去实现协议的处理
  • 发送一个请求,然后koa一层一层中间件处理,然后响应给客户端
  • 洋葱模型,一层一层过滤,在反向响应,先进后出,顺序执行

安装配置koa

要求:node>7.6.0

安装:

npm install -S koa

简单实例代码

const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
  ctx.body = "Hello,koa"
})
app.listen(3000)

常用中间件

中间件

  • koa-router 路由

安装:

npm install -S koa-router

解决的问题:

针对不同的 api返回不同的 function

示例代码:

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

/**
 * 1、request,method,respond
 * 2、api url => function
 * 3、ctx,async
 */
router.get('/', ctx => {
  console.log(ctx.request)
  ctx.body = "Hello,koa"
})
router.get('/api', ctx => {
  console.log(ctx.request)
  ctx.body = "Hello,api"
})

app.use(router.routes())
  .use(router.allowedMethods)

app.listen(3000)

router前缀

router.prefix('/api')

这里需要切记的是,router.prefix('/api')不要随意乱加,否则会引起接口调用错乱,比如以下代码:

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
router.get('/', ctx => {
  console.log(ctx.request)
  ctx.body = "Hello word"
})
router.get('/api', ctx => {
  console.log(ctx.request)
  ctx.body = "Hello,api"
})
router.prefix('/api')
router.post('/post', async (ctx) => {
  let { body } = ctx.request
  console.log(body)
  console.log(ctx.request)
  ctx.body = {
    ...body
  }
})
app.use(router.routes())
  .use(router.allowedMethods)
app.listen(3000)

在输入localhost:3000/api发送get请求,可能返回的是 Hello word。

  • koa-body 协议解析

    安装:

    npm install -S  koa-body 
    

    解决的问题:比如处理一些json数据

    示例代码:

    const koaBody = require('koa-body')
    router.post('/post', async (ctx) => {
      let { body } = ctx.request
      console.log(body)
      //console.log(ctx.request)
      ctx.body = {
        ...body  //ES6扩展运算符
      }
    })
    
    app.use(koaBody())
    

    可以向koa发送post请求,请求为json格式,例如以下:

    {
        "name": "vue",
        "age": "22",
        "email": "youremail@qq.com"
    }
    

    此时控制台打印出请求过来的json数据 如果把app.use(koaBody())去掉不引用,控制台将打印出undefined,也可以试试其它发送其他格式的数据,看看控制台是否打印请求过来的数据,这也是koaBody()的用处了,但是缺点就是不能格式化请求的数据,请求过来是什么就是什么

  • koa/cors 跨域处理

  • koa-json 格式化json数据

    安装:

    npm install -S koa-json
    

    示例代码:

    const json = require('koa-json')
    
    app.use(json({ pretty: false, param: 'pretty' }))
    

    只要在B端加上参数pretty就能格式化json参数

常用api

app.use 使用中间件

app.listen 监听端口的作用

app.on

koa执行顺序

  • 按app.use写的顺序执行,也就是use哪个中间件,哪个就执行,遇到next就继续执行下一个,没有next koa默认终止

  • 在next后面写逻辑代码,执行的顺序就是反向一层一层出去,例如以下代码执行后的结果就是

    this is a middleware!
    this is a middleware2!   
    this is a middleware3!   
    this is a middleware3end!
    this is a middleware2end!
    this is a middleware1!end:
    

    这也是koa的洋葱模式,这样的好处是有些数据要经过其他中间件处理后才能使用

示例代码:

const Koa = require('koa')
const app = new Koa()

const middleware = function async (ctx, next) {
  console.log('this is a middleware!')
  //console.log(ctx.request.path)
  next()
  console.log('this is a middleware1!end')
}
const middleware2 = function async (ctx, next) {
  console.log('this is a middleware2!')
  //console.log(ctx.request.path)
  next()
  console.log('this is a middleware2end!')
}
const middleware3 = function async (ctx, next) {
  console.log('this is a middleware3!')
  //console.log(ctx.request.path)
  next()
  console.log('this is a middleware3end!')
}

app.use(middleware)
app.use(middleware2)
app.use(middleware3)

app.listen(3000)

koa的async/await

好处:有一些操作需要数据库查询,需要等待,异步就很好的解决了这个问题,先给出一个任务,继续执行剩下的任务

示例代码:

router.get('/async', async (ctx) => {
  let result = await new Promise((resolve) => {
    setTimeout(function () {
      resolve('Hello 2s later')
    }, 2000)
  })
  ctx.body = result
})

github地址:https://github.com/LSFCXZ/koademo.git

posted on 2020-12-06 12:58  VUE林  阅读(113)  评论(0)    收藏  举报