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的集合
标签:index,koa,app,ctx,koa2,router From: https://www.cnblogs.com/nlx123/p/16800520.html