zoukankan      html  css  js  c++  java
  • 自定义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
    
    
  • 相关阅读:
    背景样式、列表样式、变形样式、过渡动画
    边框样式、段落样式、背景样式
    属性选择符、字体样式和元素样式
    Targets选项下Other linker flags的设置
    OC金额转大写
    输入手机号码 和 金额有效性的判断
    iOS手势冲突问题
    解决iOS手势冲突问题
    iOS开发 字符串的转化 小技巧
    iOS开发添加pch文件
  • 原文地址:https://www.cnblogs.com/raind/p/11826759.html
Copyright © 2011-2022 走看看