美文网首页
Koa 全解

Koa 全解

作者: littleyu | 来源:发表于2020-07-18 17:38 被阅读0次

Koa 的时间线

Express

  • 2016 年 6 月,TJ 开始编写 Express
  • 2014 年发展到 v0.12,基本成熟,移交给 StrongLoop

Koa

  • 2013 年 8 月, TJ 开始编写 Koa
  • 2015 年 8 月,Koa 发布 v1.0.0 版本

Node.js

  • 2013 年 3 月,Node.js v0.12 发布
  • 2014 年 12 月,io.js 不满 Node.js 的管理发起分裂
  • 2015 年 2 月,Node.js v0.12 发布
  • 2015 年 9 月,Node.js 与 io.js 合并为 Node.js v4.0

Koa对 Node.js 的支持

  • 2015 年 2 月,Koa 放弃对 Node v0.11 以下的支持,并开始支持 io.js
  • 2015 年 10 月,Koa 放弃对 Node v4.0 以下的支持,并用 ES6 重写所有代码,发布 v2.0.0 内测版

Koa 对比 Express

编程模型不同

  • Express 的中间件是线型
  • Koa 的中间件是 U 型

对语言特性的使用不同

  • Express 使用回调函数 next()
  • Koa v1.x 使用 generator 语法
  • Koa v2.x 使用 async / await 语法

所以
2011 ~ 2016 年,你大概率会使用 Express
2017 年之后,你可能会使用 Koa

Koa 的中间件模型

运行顺序

API

app.xxx

  • app.env
  • app.proxy
  • app.subdomainOffset
  • app.listen()
  • app.callback()
  • app.use(fn) -- 插入中间件 fn
  • app.keys
  • app.context
  • app.on('error', fn) -- 错误处理
  • app.emit -- 触发事件

ctx.xxx

  • ctx.req // Node.js 封装的请求
  • ctx.res
  • ctx.request // Koa 封装的请求
  • ctx.response
  • ctx.state -- 跨中间件分享数据
  • ctx.app
  • ctx.cookies.get / set
  • ctx.throw
  • ctx.assert
  • ctx.respond 不推荐使用

ctx.request.xxx

  • request.header
  • request.headers // as alias request.header
  • request.method
  • request.length
  • request.url
  • request.origin
  • request.href
  • request.path
  • request.quertstring
  • request.search
  • request.host
  • request.hostname
  • request.URL
  • request.type
  • request.charset
  • request.query
  • request.fresh
  • request.stale
  • request.protocol
  • ...
  • request.idmpotent
  • request.get(field)

ctx.response.xxx

  • response.header
  • response.headers
  • response.socket
  • response.status
  • response.message
  • response.length
  • response.body x 5
  • response.get()
  • response.set() x 2
  • response.append()
  • response.type
  • response.is()
  • response.redirect(url, [alt])
  • response.attachment()
  • response.headerSent
  • response.flushHeaders()
  • ...

框架推荐

Next.js / Nuxt / Nest

相关文章

  • Koa 全解

    Koa 的时间线 Express 2016 年 6 月,TJ 开始编写 Express 2014 年发展到 v0....

  • Vue Koa开发实战

    简介 参考博客: 全栈开发实战:用Vue2+Koa1开发完整的前后端项目(更新Koa2)前置技能: 具备Vue和K...

  • 萌新的全栈之旅 | 登录

    前篇 萌新的全栈之旅 前言 首先要记录的是登录模块 koa2环境搭建 图省事可以直接使用koa-generator...

  • Note19 egg+ vue项目搭建入坑

    egg.js 与 vue 结合 , 使用脚手架 easywebpack-cli。 了解egg目录结构(koa) 全...

  • koa2 用到的中间件

    koa-router //koa路由 koa-bodyparser //post 获取值 koa-stat...

  • koa-router处理URL

    koa-router处理URL koa-router使用的结构const Koa = require('koa')...

  • koa 自学入门

    const Koa = require('koa');const route = require('koa-rou...

  • 【美团网项目】1.项目介绍

    高仿美团网全栈实战 技术栈:Vue全家桶 + SSR + Koa2 全栈开发美团网 vue.js 全家桶系列,包含...

  • 初见 Koa 2

    koa 和 koa 2 最大的不同是koa 2 支持 async/await。koa 通过结合 generato...

  • trello01:后端搭建

    开发依赖: koa : 后端的主框架。 koa-router:基于Koa的路由。 koa-static-cache...

网友评论

      本文标题:Koa 全解

      本文链接:https://www.haomeiwen.com/subject/gchfkktx.html