(精华)2020年7月6日 Node.js express(手写版)
原创
©著作权归作者所有:来自51CTO博客作者愚公搬代码的原创作品,请联系作者获取转载授权,否则将追究法律责任
//myexpress.js
const http = require('http');
const url = require('url');
let routers = [];
class Application {
get(path, hander) {
routers.push({
path,
method: 'get',
hander
});
}
listen2() {
const server = http.createServer(function (req, res) {
const {
pathname
} = url.parse(req.url, true);
var tet = routers.find(v => {
return v.path == pathname && req.method.toLowerCase() == v.method
})
tet && tet.hander(req, res);
})
//在Application原型上添加listen方法匹配路径, 执行对应的hander
server.listen(...arguments)
// server.listen(aa,fn)
}
}
module.exports = function () {
return new Application();
}
const express = require('./myexpress.js');
const app = express();
app.get('/',(req,res) => {
res.end('Hello world')
})
app.get('/users',(req,res) => {
res.end(JSON.stringify({name:'abcooooo'}))
})
app.get('/list',(req,res) => {
res.end(JSON.stringify({name:'list'}))
})
app.listen2(3200 , () => {
console.log('Example listen at 3200')
})