您的位置:首页 > Web前端 > Node.js

(精华)2020年7月6日 Node.js express(手写版)

2020-07-14 06:01 316 查看
//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')
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: