码迷,mamicode.com
首页 > 其他好文 > 详细

自定义express中间件

时间:2019-11-09 18:10:09      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:nts   exports   reg   header   next   exp   his   export   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

自定义express中间件

标签:nts   exports   reg   header   next   exp   his   export   express   

原文地址:https://www.cnblogs.com/raind/p/11826759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!