《狼书2 Node.js Web应用开发》 | |||
---|---|---|---|
作者 | 狼叔 | 出版社 | 电子工业出版社 |
ISBN | 978712135906 | 出版时间 | 2020.1 |
豆瓣网址 | 是否有电子版 | 微信读书 | |
阅读日期 | 2020-06-28 | 更新日期 | 2020-06-28 |
相关链接 | 备注 |
Koa
Koa是node异步流程控制的必然产物。Koa源码很少,大概600行,极其轻量的web框架。因为没有内置任何中间件,称之为 微框架或者内核更合适。
这里完全忽略 Promise 和 Generator,只关注有关 async 的部分。
二话不说,先看一个demo
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx, next) => {
const start = new Date()
console.log('log brefore await')
await next()
console.log('log after await')
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(async ctx => {
console.log('in')
ctx.body = '2'
})
app.listen(3002)
这里第一个始终是ctx,是因为使用箭头函数绑定的this不是运行的对象。等着看源码吧。
脚手架
我觉得 koa-generator
的脚手架好垃圾。
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
:
const Router = require('@koa/router')
const router = new Router({
prefix: '/'
})
router.get('my ac', '/ac', ctx => {
// ctx.json({ a: 1 })
ctx.body = 'Hello World!';
})
module.exports = router
app.js:
const index = require('router/index')
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