Koa2

Koa2 基于 Node.js 平台的下一代Web开发框架。不绑定任何的框架,干净简洁,小而精,更容易实现定制化,扩展性好。

由 Express 原班人马打造的。Express是大而全的框架。

最大特点: 利用async,避免异步嵌套问题。

运行环境: Node > v7.6+

express、koa1、koa2 区别

koa2与koa1的最大区别是koa2实现异步是通过 async/await,koa1实现异步是通过 generator/yield,而express实现异步是通过回调函数的方式。

安装 Koa

$ npm install koa -S

操作一下~

const koa = require('koa');
// 创建koa实例
const app = new koa();

// 创建一个中间件,异步函数
app.use(async ctx => {
  ctx.body = 'Hello Koa';
});

app.listen(8082, function() {
  console.log('服务启动成功');
});

koa-router

# 安装 koa-router
npm install koa-router -S 

访问 http://localhost:8082/?name=kk&age=16
http://localhost:8082/111

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

// 创建koa实例
const app = new koa();
const router = new Router();

// 配置路由
router
  // 静态路由
  .get('/', async ctx => {
    // ctx content 包括 request response
    // 已经包括原生的 res.writeHead() res.end()
    ctx.body = '主页';

    console.log(ctx.request.query); // { name: 'kk', age: '16' }
    console.log(ctx.request.querystring); // name=kk&age=16

    // 官方推荐写法
    console.log(ctx.query);
    console.log(ctx.querystring);
  })
  // 动态路由
  .get('/:id', async ctx => {
    ctx.body = '主页';
    console.log(ctx.params);  // {id: 111}
  })
  .get('/about', async ctx => {
    ctx.body = '介绍页';
  });

// 启动路由
app.use(router.routes())
  // 官方推荐写法 
  .use(router.allowedMethods());

跟 Express 写法大同小异,不会的就看看文档。

中间件与模版渲染

中间件

洋葱模型(koa-compose),

  1. 有统一的上下文ctx(contxt)
  2. 先进后出,像栈一样。通过next() 对先进后出控制
  3. 提前结束机制

当程序执行到 await next()的时候会暂停当前程序,进入到下一个中间件,处理完后才会再回过头来继续处理。

const m1 = async (ctx, next) => {
  console.log(1);
  await next();
  console.log(6);
}

const m2 = async (ctx, next) => {
  console.log(2);
  await next();
  console.log(5);
}

const m3 = async (ctx, next) => {
  console.log(3);
  await next();
  console.log(4);
}

app
  .use(m1)
  .use(m2)
  .use(m3);

// 1
// 2
// 3
// 4
// 5
// 6
koa-compose

中间件类类型

  • 应用级中间件:vue全局导航守卫
  • 路由级中间件:独享路由守卫
  • 错误处理中间件:应用级中间件,处理错误,进行错误兜底
  • 第三方中间件:koa-bodyparser等

跟Express 差不多,就不再多介绍了,不会的就去看Express的用法吧。

模版渲染引擎

通常使用 koa-swig

koa 就是简便,没有内置中间件,需要什么就下载什么。

用的比较多的多的库 koa-static koa-bodyparser

总结

推荐使用框架的一些小想法🧐

KoaExpress
新项目原来已有的老项目,迁移不方便
定制化,喜欢自己瞎搞的喜欢一体的,可以快速集成开发
Last Updated:
Contributors: kk