Koa2 框架
koa2 是什么
- koa2 是 nodejs web server 框架
- 什么是框架 frame(类比 Vue)
- 封装原生代码的 API
- 规范流程和格式
- 让开发人员更加关注于业务代码,提高开发效率
- 框架 frame 和库 lib 的区别
- 框架是唯一的库,,就可以共存
- 框架关注全流程,,库关注单个功能
- 类比 Vue 和 lodash
- 文档 : https://koa.bootcss.com/
- 通过 async/await 语法高效编写 web server
- 中间件机制,,能合理拆分业务代码
- koa2 安装和使用
- 初始化 npm init
- 安装 npm install koa --save
- 基本使用
const Koa=require('koa')
const app=new Koa()
// ctx 读音 context 上下文
app.use(async(ctx)=>{
ctx.body='hello world'
})
app.listen(3000)// web server 监听 3000 端口
koa2 环境搭建-创建项目
-
使用脚手架 koa-generator 创建 koa2 项目
-
介绍项目的目录和文件
-
在项目中新建一个路由
-
类似 vue-cli
-
npm install -g koa-generator
-
koa2 --version
-
koa2 test4
-
cd test4
-
npm install
新建路由
- routes -> comments.js
const router = require('koa-router')()
router.prefix('/api')//前缀
//定义路由:模拟获取留言板列表
router.get('/list', async (ctx) => {
ctx.body = 'api list'
})
//定义路由:模拟创建留言
router.post('/create', async (ctx) => {
ctx.body = 'api create'
})
module.exports = router;
- app.js
// 引用路由
const comments=require('./routes/comments')
// routes 注册路由
app.use(comments.routes(),comments.allowedMethods())
// allowedMethods() 对于 404 或者返回是空的情况,的一种补充
koa2 处理 http 请求
- 如何接收和返回数据
- ctx 即 res 和 req 的集合
- querystring 和 Request body
- Response body 和 Content-type
- routes -> comments.js
const router = require('koa-router')()
router.prefix('/api')//前缀
//定义路由:模拟获取留言板列表
router.get('/list', async (ctx) => {
const query = ctx.query //req 功能
console.log('query', query)
// ctx.body = 'api list' //res 功能
ctx.body = {
errno: 0,
data: [
{ content: '留言 1', user: '张三' },
{ content: '留言 2', user: '李四' },
{ content: '留言 3', user: '无' },
]
}
})
//定义路由:模拟创建留言
router.post('/create', async (ctx) => {
const body = ctx.request.body //request body
console.log('body', body)
ctx.body = {
errno: 0,
message: '成功'
}
})
module.exports = router;
koa2 中间件
- 什么是中间件
- 一个流程上,独立的业务模块
- 可扩展,可插拔
- 类似于工厂的流水线
- 为什么使用中间件
- 拆分业务模块,使代码清晰
- 统一使用中间件,使得各业务代码都规范标准
- 扩展性好,易添加,易删除
-
模拟登录功能
- 登录校验,可使用中间件来实现
- 假如所有的接口(路由)都需要登录校验
- 假如只有一部分接口,需要登录校验
app.js //模拟登录 (为了使用中间件) app.use(async(ctx,next)=>{ const query=ctx.query if(query.user==='zhangsan'){ //模拟登录成功 await next() //执行下一步中间件 }else{ //模拟登录失败 ctx.body='请登录' } })
koa2 洋葱圈模型-介绍
- 中间件机制,是 koa2 的精髓
- 每个中间件都是 async 函数
- 中间件的运行机制,就像洋葱圈
koa2 洋葱圈模型-async 语法
//演示 async await 执行顺序
//加载一张图片
async function getImg (url = '') {
await fetch(url) //加载图片
}
async function fn () {
const url = 'http://img3.sycdn.imooc.com/5a9fc8070001a82402060220-140-140.jpg'
const start = Date.now() //记录当前时间
await getImg(url) //调动, 加载图片
const ms = Date.now() - start //计算时间差
console.log( 加载图片花费了 ${ms} 毫秒 )
}
// fn()
async function A () {
console.log('A 开始')
await fn()
console.log('A 结束')
}
A()
//1.fn(B) 2.getImg(C) 3.fn(B)
koa2 洋葱圈模型-代码演示
//演示 koa2 中间件的洋葱圈模型
const Koa = require('koa')
const { set } = require('koa/lib/response')
const app = new Koa()
//logger ctx=req+res
app.use(async (ctx, next) => {
await next() //执行下一个中间件
const rt = ctx.response.get('X-Response-Time')// 获取时间差
console.log(`${ctx.method} ${ctx.url} - ${rt}`)
})
//x-response-time
app.use(async (ctx, next) => {
const start = Date.now()
await next() //执行下一个中间件
const ms = Date.now() - start //计算时间差,例如 80
ctx - set('X-Response-Time', `${ms}ms`) //记录/设置 时间差
})
//response
app.use(async (ctx, next) => {
ctx.body='Hello world'
})
app.listen(3000)
console.log('koa2 已经开始监听 3000 端口')
洋葱圈模型-小结
- 中间件机制: 业务模块的划分
- 洋葱圈模型:中间件的执行机制
- 两者要分开来看,不要混在一起
MongoDB 数据库
- 存储数据,要用专业的数据库软件
- 数据库是一个独立的系统,和服务端语言无关
- 数据库有很多,我们选择 mongodb
- 数据库是一个非常复杂的软件
- 提供高效的存储和查询操作(还有条件,排序等)
- 能满足各个业务场景的复杂操作
- 和任何 web server 的语言,框架,都可连接
- 常见的数据库有 mongodb [mysql sqlserver oracle]
- 分类:非关系型数据库, [关系型数据库]
- mongodb 易学易用,适合初学者学习
https://www.mongodb.com/try/download/community
- D:\professional\MongoDB\bin>mongod.exe --dbpath D:\professional\MongoDB\data\db
- "port": 27017 默认端口

