02 用koa 说 Hello World

2-1 koa 简介

2-2 安装搭建第一个 Koa 程序

2-3 Koa中间件与洋葱模型

2-1 koa 简介

  • 由 Express 幕后的原班人马打造
  • web 应用和 API 开发领域
  • 更小、更富有表现力、更健壮
  • 利用async函数,丢弃回调函数
  • 增强错误处理:try catch
  • 没有捆绑任何

2-2 安装搭建第一个 Koa 程序

  • 初始化项目
  • 安装 Koa
  • 编写 Hello World
  • 学习自动重启
npm i koa --save

index.js

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

app.use((ctx) => {
    ctx.body = 'Hello World'
})

app.listen(3000)

2-3 Koa中间件与洋葱模型

  • 学习 async await
  • 学习编写 Koa 中间件
  • 学习洋葱模型

回调写法

fetch('//api.github.com/users').then(res => 
    res.json()).then(json => {console.log(json)
    fetch('//api.github.com/users/lewis617').then(res => 
        res.json()).then(json => {console.log(json)
    })
})

async await

(async () => {
    const res = await fetch('//api.github.com/users')
    const json = await res.json()
    console.log(json)
    const res2 = await fetch('//api.github.com/users/lewis617')
    const json2 = await res2.json()
    console.log(json2)
})()

中间件执行

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

app.use(async (ctx, next) => {
    await next()
    console.log(1)
    ctx.body = 'Hello World'
})

app.use(async (ctx, next) => {
    await next()
    console.log(2)
})

app.listen(3000)

输出: 2 1
由于在第一个中间件中用到了async await,await next()到了第二个中间件执行完打印2然后打印第一个中间件的1.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值