• Koa对比Express 开启一个Koa服务


    Koa对比Express

    Express的中间件是线型的,调用next就放行,执行下一个中间件
    Koa的中间件是U型,也叫做洋葱模型, 即use多个中间件,先按中间件书写的顺序执行每个中间件awaitnext调用之前的代码,然后按中间件书写的逆序执行中间件await next之后的代码

    Koa1使用generator语法
    Koa2使用async/await语法

    Koa 的ctx.req和ctx.request分别来自于Nodejs和Koa自身

    开启一个Koa服务

    安装

    npm i --save-dev @types/koa
    npm i koa 
    tsc --init
    ts-node-dev 01koa_server.ts
    

    import Koa from 'koa'
    
    const app = new Koa()
    
    app.use(async (context) => {
        context.body = 'hello koa'
    })
    
    app.listen(3000, () => console.log('server run at port 3000'))
    

    中间件

    访问3000端口,输出什么?

    import Koa from 'koa'
    
    const app = new Koa()
    
    app.use(async (context,next) => {
        context.body = '1'
        await next()
        context.body += ' 3'
    })
    
    app.use(async (ctx,next)=>{
        ctx.body += ' 2'
        await next()
        ctx.body += ' 4'
    })
    
    app.listen(3000, () => console.log('server run at port 3000'))
    

    答:
    1,2,4,3

    联想洋葱模型,即U型
    先走到1,2,此时到达U的拐点,然后是4,3

    设置响应头

    import Koa from 'koa'
    
    const app = new Koa()
    
    app.use(async (context, next) => {
        context.body = '1'
        await next()
        context.body += ' 3'
    })
    
    app.use(async (ctx, next) => {
        ctx.body += ' 2'
        await next()
        ctx.body += ' 4'
    })
    
    // 设置响应头
    app.use(async (ctx, next) => {
        ctx.set('Content-Type', 'text/html;charset=utf-8')
        await next()
    })
    
    
    app.listen(3000, () => console.log('server run at port 3000'))
    
  • 相关阅读:
    redis持久化的方式RDB 和 AOF
    centos7搭建mysql-5.7.22主从复制
    Vue项目上线后刷新报错404问题(apache,nginx,tomcat)
    Zabbix监控华为交换机
    Zabbix数据库清理历史数据
    MySQL增删改查基本语句
    什么是SQL注入式攻击?
    .NET面试题(二)
    .NET面试题(一)
    .NET面试题(三)
  • 原文地址:https://www.cnblogs.com/ltfxy/p/16002546.html
Copyright © 2020-2023  润新知