zoukankan      html  css  js  c++  java
  • Node web 框架

      Node web 框架 - Koa2

      刚刚写了一个简单的 Express 流程的实现,来理解 Express 的原理。

      相比 Express,Koa2 更加的简单。

      1、Koa2 也是通过 use 添加函数来处理请求,不过是一个异步函数,并且传入的是一个上下文

      2、Koa2 在处理请求的时候,首先创建一个当前请求相关的上下文

      3、传入的异步函数,所以用 await 来实现一层一层处理上下文后( 洋葱模式的形式 )

      4、最后通过上下文的 body 来完成数据返回

      简单的代码实现:

    const http = require('http')
    
    class App {
        constructor() {
            this.middleware = []
        }
    
        use(fn) {
            this.middleware.push(fn)
        }
    
        // 链式模型
        compose() {
            const {middleware} = this
            return async function (ctx) {
                let index = 0
                const next = async function () {
                    let handle = null
                    while (!handle && index < middleware.length) {
                        handle = middleware[index++]
                    }
                    if (handle) return await handle(ctx, next)
                    if (!handle) Promise.resolve()
                }
                await next();
            }
        }
    
        listen() {
            const callback = async (req, res) => {
                const handle = this.compose()
                const context = {
                    response: res,
                    request: req,
                    app: this
                }
                await handle(context)
                res.end(context.body)
            }
            const server = http.createServer(callback)
            server.listen.apply(server, arguments)
        }
    }
    
    const app = new App()
    app.use(async (ctx, next) => {
        ctx.body = 'one
    '
        await next()
        ctx.body += 'two
    '
    })
    app.use(async (ctx, next) => {
        ctx.body += 'three
    '
        await next()
        ctx.body += 'four
    '
    })
    app.listen(3300)
    

      

      代码仅供理解!

    博客园小结巴巴: https://www.cnblogs.com/jiebba

  • 相关阅读:
    day1记一次无列名注入
    无参数RCE
    ThinkPHP 5.x远程命令执行漏洞
    phpmyadmin4.8.1文件包含漏洞
    foreach循环导致变量覆盖
    绕过空格的报错注入
    布尔盲注payload补充
    php后台验证两种方式绕过
    CentOS yum 配置阿里镜像
    CentOS通过yum安装配置Java环境
  • 原文地址:https://www.cnblogs.com/jiebba/p/12780891.html
Copyright © 2011-2022 走看看