koa2

koa 安装

npm init
npm i koa --save

index.js

const Koa = require('koa')
const app=new Koa()

app.use(async(ctx)=>{
     ctx.body = 'hello'
})

app.listen(3000

koa2环境搭建

脚手koa-generator创建koa2项目

安装
npm install -g koa-generator
查看版本号
koa2 --version
创建名为test的koa2的文件夹
koa2 test
cd test
npm init

文件和目录

app.js 入口文件

error hander 错误处理器
onerror(app)
error-handling
app.on('error',(err.ctx)=>{})

middlewares 中间件 (app.use(...))

request body 转换
bodyparser({
enableTypes:['json','form','text']
})

json() request body json转换

logger() 日志打印格式

_dirname 当前目录 在public文件夹下images
static(_dirname + '/public') 静态文件服务 : 可直接访问 localhost:3000/images/1.jpg

服务端模板引擎
views(_dirname+'views',{extension:'pug'})

routes 路由 allowedMethods()对于404或者放回是空的情况的另一补充
const index = reqiure('./routes/index')
app.use(index.routes(), index.allowedMethods()

新建路由

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

前缀
router.prefix('/api')

定义路由 router.get/post(path,async(ctx)=>{内容})
router.get('/list',async(ctx)=>{
  ctx.body="hello world"
})

输出
module.exports = router

koa2处理http请求

接受和返回数据

ctx 即res和req的集合
query 和 request.body
response body 和 Content-type

req功能
const query = ctx.query
const body =ctx.request.body

res功能
ctx.body={
      errno:0,
      data:[
      {content:'留言1',user:'张三'},
      {content:'留言2',user:'张三2'},
        ]
}

koa2中间件

中间件 : 一个流程上,独立的业务模块,可扩展,可插拔,拆分业务模块,是代码清晰,统一使用中间件,使得各业务代码都规范标准

app.use(..)都是中间件
路由也是中间件(只不过限制了url规则)

koa2洋葱圈模型

中间件机制,是koa2的精髓
每个中间件都是async函数
中间件的运行机制,就行洋葱圈

和中间件模型的关系

中间件机制:业务模块的划分
洋葱圈模型:中间件的执行机制

posted @   strawberry&cigarette  阅读(98)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示