• 自定义express中间件


    const http = require('http')
    
    class LikeExpress {
      constructor() {
        this.middleList = []
        this.routes = {
          all: [],
          get: [],
          post: []
        }
      }
      // 处理参数
      register(path) {
        const info = {}
        const slice = Array.prototype.slice
        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 info = this.register.apply(this, arguments)
        this.routes.all.push(info)
      }
      get() {
        const info = this.register.apply(this, arguments)
        this.routes.get.push(info)
      }
      post() {
        const info = this.register.apply(this, arguments)
        this.routes.post.push(info)
      }
      match(url, method) {
        let stack = []
        if (url === 'favicon.ico') {
          return stack
        }
        let curRoutes = []
        curRoutes = curRoutes.concat(this.routes.all).concat(this.routes[method])
        curRoutes.forEach(route => {
          if (url.indexOf(route.path) === 0) {
            stack = stack.concat(route.stack)
          }
        })
        return stack
      }
      handle(list, req, res) {
        const next = () => {
          const middware = list.shift()
          if (middware) {
            middware(req, res, next)
          }
        }
        next()
      }
      callback() {
        return (req, res) => {
          res.json = data => {
            res.setHeader('Content-Type', 'application/json')
            res.end(JSON.stringify(data))
          }
          const url = req.url
          const method = req.method.toLowerCase()
    
          const resultList = this.match(url, method)
          this.handle(resultList, req, res)
        }
      }
      listen(...args) {
        const server = http.createServer(this.callback())
        server.listen(...args)
      }
    }
    
    module.exports = LikeExpress
    
    
  • 相关阅读:
    关于正则表达式的递归匹配问题
    给程序添加启动画面
    C#中的ICollection接口
    C#基本线程同步
    C# 图片裁剪代码
    .NET程序性能的基本要领
    C# 6与VB 12即将加入模式匹配
    Python实例---利用正则实现计算器[FTL版]
    Python实例---利用正则实现计算器[参考版]
    Python学习---重点模块之subprocess
  • 原文地址:https://www.cnblogs.com/raind/p/11826759.html
Copyright © 2020-2023  润新知