Koa2介绍
koa2简介
基于Node.js平台的web开发框架
由Express原班人马打造
框架名 | 作用 | 异步处理 |
---|---|---|
Express | web框架 | 回调函数 |
Koa | web框架 | Generator + yield |
Koa2 | web框架 | async/await |
依赖环境Node v7.6.0及以上
Koa2特点洋葱模型的中间件
支持async\await
Koa2快速上手
快速上手
- 检查Node的环境
node -v - 安装Koa
npm init -y
npm install koa - 创建并编写app.js文件
创建Koa对象
编写响应式函数(中间件)
监听端口 - 启动服务器
node app.js
中间件的特点
- Koa对象通过use方法加入一个中间件
- 一个中间件就是一个函数
- 中间件的执行顺序符合洋葱模型
- 内层中间件能否执行取决于外层中间件的next函数是否调用
- 调用next函数得到的是promise对象
项目准备
项目准备 → 总耗时中间件 → 响应头中间件 → 业务逻辑中间件 → 允许跨域
项目准备
文件目录结构
总耗时中间件
- 第一层中间件
- 计算执行事件
一进入时记录开始事件
其他所有中间件执行完后记录结束时间
两者相减 - 设置响应头
X-Response-Time: 5ms
// 计算服务器消耗时长的中间件
module.exports = async (ctx, next) => {
// 记录开始时间
const start = Date.now()
// 让内层中间件得到执行
await next()
// 记录结束的时间
const end = Date.now()
// 设置响应头 X-Response-Time
const duration = end - start
// ctx.set设置响应头
ctx.set('X-Response-Time', duration + 'ms')
}
响应头中间件
- 第二层中间件
- 获取mime类型
application/json - 设置响应头
Content-Type:application/json; charset=UTF-8
// 设置响应头的中间件
module.exports = async (ctx, next) => {
const contentType = 'application/json; charset=utf-8'
ctx.set('Content-Type', contentType)
ctx.response.body = '{"success": true}'
await next()
}
}
业务逻辑中间件
- 第三层中间件
- 读取文件内容 ( http://localhost:8888/api/seller )
获取请求的路径,拼接文件路径
读取该路径对应文件的内容 - 设置响应体
ctx.response.body
// 处理业务逻辑的中间件,读取某个json文件的数据
const path = require('path')
const fileUtils = require('../utils/file_utils')
module.exports = async (ctx, next) => {
// 根据url
const url = ctx.request.url // /api/seller ../data/seller.json
let filePath = url.replace('/api', '') // /seller
filePath = '../data' + filePath + '.json' // ../data/seller.json
filePath = path.join(__dirname, filePath)
try {
const ret = await fileUtils.getFileJsonData(filePath)
ctx.response.body = ret
} catch (error) {
const errorMsg = {
message: '读取文件内容失败',
status: 404
}
ctx.response.body = JSON.stringify(errorMsg)
}
await next()
}
允许跨域
- 实际是通过Ajax访问服务器
- 同源策略
同协议、同域名、同端口
当前页面的地址和Ajax获取数据的地址 - 设置响应头
// 设置响应头的中间件
module.exports = async (ctx, next) => {
const contentType = 'application/json; charset=utf-8'
ctx.set('Content-Type', contentType)
ctx.set("Access-Control-Allow-Origin", "*")
ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
// 进行下一步
await next()
}