直接上代码
创建x-express.js
const http = require('http')
const url = require('url')
const router = []
class Appliction {
get(path, handler) {
router.push({
path,
method: 'get',
handler
})
}
listen() {
const server = http.createServer((req, res) => {
// console.log(url.parse(req.url, true))
const { pathname } = url.parse(req.url, true)
for(const route of router) {
const { path, method, handler } = route
if(pathname === path && method === req.method.toLocaleLowerCase()) {
// return handler(req, res)
handler(req, res)
}
}
})
server.listen(...arguments)
}
}
module.exports = function createAppliction() {
return new Appliction()
}
创建 index.js
const express = require('x-express')
const app = express()
app.get('/', (req, res) => {
res.end('123')
})
app.get('/users', (req, res) => {
res.end('456')
})
app.listen(3000, () => {
console.log('listen port at 3000')
})
执行 node index.js