koa框架学习
简介:koa是原班的express框架人员开发,是一个全新的web框架,致力于成为web应用和API开发领域中的一个更小的、更富有表现力、更健壮的基石。
特点: 利用async函数丢弃回调函数,并增强错误处理。Koa没有预设任何预置的中间件,可快速的编写服务端应用程序。
核心概念
-
Koa Application(应用程序)
-
Context(上下文)
-
Request(请求) Response(响应)
第一个koa应用
-
首先新建一个文件夹,在文件夹中执行
npm init -y
,去生成一个package.json
文件 -
执行
npm install -S koa
去安装koa应用 -
新建一个index.js文件,在文件中书写
const Koa = require('koa') const app = new Koa() app.use(async ctx => { ctx.body = 'Hello world!!' }) app.listen(3000) // 使我们的Koa程序运行在3000端口
-
通过
node index.js
运行我们的koa应用,在浏览器中输入localhost:3000
至此我们的第一个
hellow world koa
应用就已经成功完成啦!
koa router
简介: koa-router是一个路由管理模块的中间件,基于上面我们的第一个koa程序继续进行改进
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
router.get('/', ctx => {
ctx.body = 'Hello world!!'
})
router.get('/api', ctx => {
ctx.body = 'this routes is /api!!'
})
app.use(router.routes()) // 将我们上面申请的路径进行注册
.use(router.allowedMethods()) // 拦截器,拦截一些没有的请求,会直接返回4xx或者5xx错误
app.listen(3000)
此时,我们访问localhost:3000/api
这时候就会返回对应的值
koa工作原理
-
执行的顺序: 顺序执行
-
回调的顺序: 方向执行
-
先进后出
🧅洋葱原理
一个简单的说明例子
const Koa = require('koa') const app = new Koa() const middleware1 = function async(ctx, next) { console.log(ctx.request.path) console.log('hello this is middleware1') next() console.log('end the middleware1') } const middleware2 = function async(ctx, next) { console.log(ctx.request.path) console.log('hello this is middleware2') next() console.log('end the middleware2') } const middleware3 = function async(ctx, next) { console.log(ctx.request.path) console.log('hello this is middleware3') next() console.log('end the middleware3') } app.use(middleware1) .use(middleware2) .use(middleware3) app.listen(3000)
/apiss hello this is middleware1 /apiss hello this is middleware2 /apiss hello this is middleware3 end the middleware3 end the middleware2 end the middleware1
由以上的输出结果不难理解,在我的理解中就是按照js的上下文顺序执行,当遇到next函数的时候会将改ctx继续交给下一个middleware去执行。如果这里没有使用next函数则koa会认为我们已经执行完毕,会直接将结果返回给用户。而我们使用了next函数则可以理解为将下列的中间件插入当前next函数位置。故有先进后出原则;