Koa 是由 Express 原班人马打造的超轻量服务端框架css
与 Express 相比,除了自由度更高,能够自行引入中间件以外,更重要的是使用了 ES6 + async,从而避免了回调地狱html
不过也是由于代码升级,因此 Koa2 须要 v7.60 以上的 node.js 环境node
1、建立项目web
手动建立一个项目目录,而后快速生成一个 package.json 文件npm
npm init -y
安装 koa //当前版本 2.4.1json
npm install koa -S
而后建立一个 app.js浏览器
// app.js const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Wise Wrong'; }); app.listen(3000);
最后在 package.json 中添加启动指令app
一个最基础的 koa 应用就这样完成了框架
能够执行 npm start 并在浏览器访问 http://localhost:3000/ 查看效果koa
若是以为手动建立项目太过繁琐,可使用脚手架 koa-generato 来生成项目
npm install koa-generator -g
koa2 project_name
而后在项目下 npm install 安装依赖,npm start 启动项目
若是是刚接触 koa,建议先看完这篇博客,再使用脚手架工具,这样能更好的理解各个依赖包的做用
2、配置路由
上面 app.js 中有一个 ctx,这是一个 Koa 提供的 Context 对象,封装了 request 和 response
每一次 HTTP Request 都会建立一个 Context 对象
咱们能够经过 Context.request.path 来获取用户请求的路径,而后经过 Context.response.body 给用户发送内容
Koa 默认的返回类型是 text/plain,若是要返回一个 html 文件(或者一个模块文件),就须要修改 Context.response.type
另外,Context.response 能够简写,好比 Context.response.type 简写为 Context.type,Context.response.body 简写为 Context.type
在项目下建立一个存放 html 文件的目录 views,并在该目录下建立一个 index.html,而后修改 app.js
// app.js
// 原生路由 const Koa = require('koa'); const fs = require('fs'); const app = new Koa(); app.use(async (ctx, next) => { if (ctx.request.path === '/index') { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html'); } else { await next(); } }); app.listen(3000);
而后在浏览器中访问 http://localhost:3000/index 就能看到 index.html 页面,而访问别的地址则是 not found
这样处理 url 显得特别笨拙,因此咱们须要引入路由中间件 koa-router
npm install koa-router -S
须要注意的是,在导入 koa-router 的时候,须要在末尾加一个括号:
const router = require('koa-router')();
至关于:
const koaRouter = require('koa-router'); const router = koaRouter();
建立一个 routes 目录,用来存放路由文件,并在目录下建立 index.js
// routes/index.js const fs = require('fs'); const router = require('koa-router')() router.get('/index', async (ctx, next) => { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html'); }); module.exports = router
这里还可使用 prefix 方法,为文件中的全部接口添加一个 baseUrl
// router.prefix('/about')
修改 app.js
// app.js const Koa = require('koa'); const app = new Koa(); const index = require('./routes/index') app.use(index.routes(), index.allowedMethods()) app.listen(3000);
上面的 allowedMethods 用于校验请求的方法,若是用 post 请求访问 get 接口,就会直接返回失败
另外,还能够在 url 中添加变量,而后经过 Context.params.name 访问
router.get('/about/:name', async (ctx, next) => { ctx.body = `I am ${ctx.params.name}!`; });
3、静态资源
在上面的 index.html 中,若是须要引入 css 等静态资源,就须要用到 koa-static
npm install koa-static -S
建立一个目录 public 用来存放静态资源
而后在 app.js 中添加如下代码
const static = require('koa-static'); // 将 public 目录设置为静态资源目录 const main = static(__dirname + '/public'); app.use(main);
事实上,这三行代码还能够优化
app.use(require('koa-static')(__dirname + '/public'));
而后就能在 index.html 中引入对应的文件了
4、模板引擎
上面的路由是使用 fs 模块直接读取 html 文件
开发的时候更推荐使用 koa-views 中间件来渲染页面
npm install koa-views -S
在 app.js 中将 views 目录设定为模版目录
const views = require('koa-views') app.use(views(__dirname + '/views'));
而后在路由文件中,就能使用 render 方法了
// routes/index.js const router = require('koa-router')() router.get('/index', async (ctx, next) => { await ctx.render('index'); }); module.exports = router
以上是直接渲染 html 文件的方法,若是要引入模板引擎,能够添加 extension 字段来设定模版类型
app.use(views(__dirname + '/views', { extension: 'pug' // 以 pug 模版为例 }))
5、结语
若是将 Express 看做 webstorm,那么 Koa 就是 sublime
当 Express 流行的时候,其冗杂的依赖项被不少开发者所诟病
因此 Express 团队将 Express 拆卸得只剩下最基本的骨架,让开发者自行组装,这就是 Koa
正如文中所说,从零开始太过繁琐,可使用脚手架 koa-generato 来快速开发
不过我更推荐,在熟悉了 Koa 以后,搭一个适合本身项目的脚手架
否则为什么不直接用 Express 呢
我想这也是 Koa 的官方文档中没有提到 generato 工具的缘由吧