Express中间件简单的实现原理

上一篇理解Express的使用之后, 再总结一篇Express中间件的简单实现原理。

我们知道Express中间件就是一个个的函数, 那么怎么让这些函数有序的执行呢? 那就需要我们调用 next 函数。其实 next函数调用的就是下一个中间件函数。

以下代码实现了简单的 app.use 注册中间件, 以及 getpost方式的中间件。其他请求方式的中间件实现同理

核心代码:

const next = () => {
    const stack = stacks.shift()
    if(stack) {
        stack(req, res, next)
    }
}
next()

stacks就是一个数组队列, 存放所有符合规则的中间件函数。遵循先进先出的原则。也就是最先注册的中间件函数最先执行。

实现代码

const http = require('http')
const slice = Array.prototype.slice

 class Express {
     constructor() {
        this.router = {
            all: [], // 匹配所有额中间件函数
            get: [],
            post: []
        }
     }

     /**
      * 这里整合中间件
      * @param {string} path 
      * @returns {object}
      */
     middlewareHandler(path) {
        const info = {}
        if (typeof path === 'string') {
            info.path = path
            info.stack = slice.call(arguments, 1)  // 中间件数组
        } else {
            info.path = '/'
            info.stack = slice.call(arguments, 0)
        }

        return info
     }

     use() {
        const allStack = this.middlewareHandler(...arguments)
        this.router.all.push(allStack)
     }

     get() {
        const getStack = this.middlewareHandler(...arguments)
        this.router.get.push(getStack)
     }

     post() {
        const postStack = this.middlewareHandler(...arguments)
        this.router.post.push(postStack)
     }

      /**
       * 
       * @param {string} method 
       * @param {string} url
       * @returns {Array} 
       */
     accordStack(method, url) {
        let stacks = []
        stacks = stacks.concat(this.router.all)
        stacks = stacks.concat(this.router[method])
        return stacks
        .filter(stack => {
            return url.indexOf(stack.path) !== -1
        }).map(item => item.stack[0])
     }

     handler(req, res, stacks) {
         // 函数表达式
        const next = () => {
            const stack = stacks.shift()
            if(stack) {
                stack(req, res, next)
            }
        }
        next()
     }

     callback() {
        return (req, res) => {
            res.json = data => {
                res.setHeader('Content-Type', 'application/json')
                res.end(JSON.stringify(data))
            }
            
            // 拿到请求的方法和url, 对中间件函数进行筛选
            const {method, url} = req
            const stacks = this.accordStack(method.toLowerCase(), url)
            this.handler(req, res, stacks)
        } 
     }

     listen(...args) {
         const server = http.createServer(this.callback())
         server.listen(...args)
     }
 }

 // 工厂模式, 导出一个实例对象
module.exports = () => {
    return new Express()
}

原文地址:https://www.cnblogs.com/qiqingfu/p/10893513.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


根据官网 入门 express
java叫接口control什么的app.get.post等等都是请求方式我们可以在游览器输入localhost端口/或者在Apifox里面写。
为了前端丢进去的时候可以直接判断中间件就是经过了这个就会被使用可以做一些自己的数据处理什么的。
Express 文件的上传和下载
运行命令下载app.js 增加中间件。
基本模板来的 后面用后就有什么加什么都行。
此篇完成 增删 刷新文件 的基本操作
最基本的创建 以及 添加了其他的一些插件 登录接口和四个接口
由于每个接口都要放就很麻烦 所以做个中间件
1importre234defstrip_operate(exp):#合并多余的操作符5exp=exp.replace("+-","-")6exp=exp.replace("--","+")7returnexp8910defcal_exp_son(exp_son):#计算两数的乘除11if&
 socket.html<script>//高级api不兼容socket.io//http单向的,socket是双向的,传输都靠tcpletsocket=newWebSocket('ws://localhost:3000')socket.onopen=()=>{//多个页面通信就是先发给服务器,服务器再发给另一个页面socket.send('我
M模式:类,表示数据的应用程序和使用验证逻辑以强制实施针对这些数据的业务规则。V视图:应用程序使用动态生成HTML响应的模板文件。C控制器:处理传入的浏览器请求的类中检索模型数据,然后指定将响应返回到浏览器的视图模板。简单练习: 1、添加ControllerHelloWorldControlle
在Node开发中免不了要使用框架,比如express、koa、koa2拿使用的最多的express来举例子开发中肯定会用到很多类似于下面的这种代码varexpress=require('express');varapp=express();app.listen(3000,function(){console.log('listen3000...');});app.use(middle
node的http创建服务与利用Express框架有何不同原生http模块与使用express框架对比:consthttp=require("http");letserver=http.createServer(function(req,res){//服务器收到浏览器web请求后,打印一句话console.log("recvreqfrombrowser");
编辑nginx文件vi/usr/local/etcginxginx.confnginx配置如下,配置后需重启nginxnginx-sreloadlocation~.*\.json{roothtml;add_header"Access-Control-Allow-Origin""*";}前端index.html<script>fetch('http://localhost:12
constexpress=require('express')constapp=express()//步骤的拆解constresult=express.static('./views')app.use(result)//再次托管一下样式表的资源目录app.use('/css',express.static('./css'))//托管JS文件目录app.use('/js&#
问题描述:最近在做毕设,express里边的中间件(body-parser)失效,req.body获取不到任何值,req.query能获取到值。一开始加body-parser中间件是有用的,直到昨天加了token之后,body-parser失效。试着把token去掉,无济于事,也不是这个问题,也有说版本对不上的,换了中间件的引入方法,还是没用!!! 后
express官网:---->传送门 expressexpress框架有许多功能,比如路由配置,中间件,对于想配置服务器的前端来说,非常便捷自从node发展之后,基于nodejs的开发框架也不断涌现出来,express就是其中之一,最近简单的写了点express框架的简单的处理请求的demo首先是安装express模块npminstall
目录问题: 操作:Win+S按键,输入“事件查看器”问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll未能加载。返回的数据为错误信息。问题:  操作:Win+S按键,输入“事件查看器” 问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll
//获取阿里云市场,快递物流记录https://market.aliyun.com/products/56928004/cmapi022273.html?spm=5176.2020520132.101.26.61f97218v18GBF#sku=yuncode1627300000//get_express_log(self::$config['web']['aliyun_AppCode']阿里云市场AppCode,缓存秒数如300秒,'快递公司代