大家好我是林三心,用了那么久express,也自己简单实现一下吧(有利于以后观看express源码)
目录结构

let http = require('http')
let url = require('url')
let querystring = require('querystring')
var util = require('util');
function createApplication() {
let app = function (req, res) {
console.log(req.method, url.parse(req.url, true), req.body)
let m = req.method.toLocaleLowerCase()
console.log(m)
let { pathname, query } = url.parse(req.url, true)
let index = 0
function next() {
if (index === app.routes.length) {
return res.end(`can not ${m} ${pathname}`)
}
let { path, method, handler } = app.routes[index++]
if (method === 'middle') {
if (path === '/' || path === pathname || pathname.startsWith(path + '/')) {
handler(req, res, next)
} else {
next()
}
} else {
if ((path === pathname || path === '*') && (method === m || method === 'all')) {
switch (method) {
case 'get':
req.query = query
break
case 'post':
}
handler(req, res, next)
} else {
next()
}
}
}
next()
res.end('hello world')
}
app.routes = []
http.METHODS.forEach(method => {
method = method.toLocaleLowerCase()
app[method] = function (path, handler) {
let layer = {
path,
method,
handler
}
app.routes.push(layer)
}
})
app.all = function (path, handler) {
let layer = {
path,
method: 'all',
handler
}
app.routes.push(layer)
}
app.listen = function () {
let server = http.createServer(app)
server.listen(...arguments)
return server
}
return app
}
module.exports = createApplication
const expressDemo = require('./expressDemo2')
let app = expressDemo()
app.get('/name', (req, res) => {
console.log(req.query.name)
res.end('get name')
})
app.post('/name', (req, res) => {
res.end('get name')
})
app.put('/name', (req, res) => {
console.log(req.query.name)
res.end('get name')
})
app.delete('/name', (req, res) => {
console.log(req.query.name)
res.end('get name')
})
app.listen(9002, 'localhost', () => {
console.log('林三心在9002')
})
主要要理解“中间件是什么”?express方便在哪里?use方法是用来干嘛的?加油!!!