自定义express中间件
2024-09-04 19:35:30
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
最新文章
- Android 登录界面与首页的设计
- 数据仓库原理<;2>;:数据仓库系统的体系结构
- Write cv::Mat to a file
- The world beyond batch: Streaming 101
- 右键TXT文件-打开方式-选择默认程序提示 windows无法访问指定设备,路经或文件.您可能没有合适的权限访问这个项目
- HTMO DOM部分---小练习;列表之间移动、日期选择、好友选中、滑动效果、滚动条效果、飞入飞出效果。
- Jquary获取页面控件的值
- 『SQL注入』 User-Agent 手工注入的探测与利用分析
- myeclipse 调试JSP页面
- web微信开发前期准备最新详细流程
- 如何将Windows7系统中“运行”历史记录全部清除
- nat的翻译类型(2)--动态nat
- Ubuntu16.04 安装NVIDIA显卡驱动
- hadoop2.7单节点
- 使用通配符和泛型:完成父子类关系的List对象的类型匹配
- CentOS下将Python的版本升级为3.x
- crontab使用说明及例子程序
- Oozie-coordinator调度
- log4cpp简单使用及踩到的坑
- 使用switchPage.js插件jQuery全屏滚动翻页