《狼书2 Node.js Web应用开发》
作者 狼叔 出版社 电子工业出版社
ISBN 978712135906 出版时间 2020.1
豆瓣网址 是否有电子版 微信读书
阅读日期 2020-06-28 更新日期 2020-06-28
相关链接 备注

《狼书2 Node.js Web应用开发》笔记 - 图1

Koa

Koa是node异步流程控制的必然产物。Koa源码很少,大概600行,极其轻量的web框架。因为没有内置任何中间件,称之为 微框架或者内核更合适。

这里完全忽略 Promise 和 Generator,只关注有关 async 的部分。

二话不说,先看一个demo

  1. const Koa = require('koa')
  2. const app = new Koa()
  3. app.use(async (ctx, next) => {
  4. const start = new Date()
  5. console.log('log brefore await')
  6. await next()
  7. console.log('log after await')
  8. const ms = new Date() - start
  9. console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  10. })
  11. app.use(async ctx => {
  12. console.log('in')
  13. ctx.body = '2'
  14. })
  15. app.listen(3002)

这里第一个始终是ctx,是因为使用箭头函数绑定的this不是运行的对象。等着看源码吧。

脚手架

我觉得 koa-generator 的脚手架好垃圾。

  1. yarn add -D koa @koa/router koa-bodyparser koa-json koa-logger koa-onerror koa-static koa-view ejs less-middleware

路由 router

由于各种原因,这里不再推荐 koa-router ,改为 @koa/router 作为路由中间件。

一个典型的路由配置文件 router/index.js

  1. const Router = require('@koa/router')
  2. const router = new Router({
  3. prefix: '/'
  4. })
  5. router.get('my ac', '/ac', ctx => {
  6. // ctx.json({ a: 1 })
  7. ctx.body = 'Hello World!';
  8. })
  9. module.exports = router

app.js:

  1. const index = require('router/index')
  2. app.use(index.routes(), index.allowedMethods())

route.use:

  • 第一个参数,基准路径。类似于prefix
  • 第二个 index.routes() 是 router对象上挂载的所有中间件,

路由实现原理

这里依赖了 path-to-regexp 作为核心依赖。

视图引擎

一般使用 koa-views 来支持第三方模板引擎,比如 ejs pug nunjucks 等

中间件

koa2中,

  • 把req,res都绑定到 ctx 上。
  • 洋葱模型,能够双向拦截,在req res都可以拦截

只关注 async 中间件。

测试

  • 使用 ava 替代 mocha 做单元测试
  • 使用 supertest 做 http测试

ava的生命周期:

  • brfore
  • after
  • cb.beforeEach
  • afterEach.cb