自定义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
优质内容筛选与推荐>>
1、【转】ASP 连接ACCESS,SQL连接数据库字符串
2、sql 累计 总分 排名
3、Carmelo Anthony nie avoir ultimatum Knicks
4、Delphi的取整函数round、trunc、ceil和floor
5、IELTS Writing Tips


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号