初识Koa

Koa简介

Koa是一个新的web框架,由Express幕后的原班人马打造,致力于成为web应用和API开发领域中的一个更小、更富有表现力、更健壮的基石。通过利用async函数, Koa帮你丢弃回调函数,并有力地增强错误处理。Koa 并没有捆绑任何中间件,而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。

Koa核心概念

◆Koa Application (应用程序)
◆Context(上下文)
◆Request(请求)、Response (响应)

Koa应用小演练

npm init -y //初始化
npm install --save koa
const Koa = require('koa')
const app = new Koa()

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

app.listen(3000)//端口号

在这里插入图片描述

koa工作原理

◆执行的顺序:顺序执行
◆回调的顺序:反向执行
◆先进后出

例子

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

const middleware = function async(ctx, next) {
    console.log("this is s middleware")

}

const middleware1 = function async(ctx, next) {
    console.log("this is s middleware1")
    next()
    console.log("this is s middleware1 ending")
}

const middleware2 = function async(ctx, next) {
    console.log("this is s middleware2")
    next()
    console.log("this is s middleware2 ending")
}

app.use(middleware1);
app.use(middleware2);
app.use(middleware);

app.listen(3000);
终端的打印结果:
node middleware.js
this is s middleware1
this is s middleware2
this is s middleware
this is s middleware2 ending
this is s middleware1 ending

Koa的特点

◆简洁
◆ async/await
◆丰富的中间件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值