koa框架学习(一)

koa框架学习


简介:koa是原班的express框架人员开发,是一个全新的web框架,致力于成为web应用和API开发领域中的一个更小的、更富有表现力、更健壮的基石。

特点: 利用async函数丢弃回调函数,并增强错误处理。Koa没有预设任何预置的中间件,可快速的编写服务端应用程序。

核心概念

  • Koa Application(应用程序)

  • Context(上下文)

  • Request(请求) Response(响应)

    koa工作原理

第一个koa应用

  1. 首先新建一个文件夹,在文件夹中执行npm init -y,去生成一个package.json文件

  2. 执行npm install -S koa去安装koa应用

  3. 新建一个index.js文件,在文件中书写

    const Koa = require('koa')
    const app = new Koa()
    
    
    app.use(async ctx => {
      ctx.body = 'Hello world!!'
    })
    
    app.listen(3000) // 使我们的Koa程序运行在3000端口
    
  4. 通过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这时候就会返回对应的值

进入/api路径

被allowedMethods方法拦截

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函数位置。故有先进后出原则;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值