看遭顶,那是一只小鳥的歡樂侧啼,那有一片亮云的消散
微信圖片_20200505203448.jpg
在現(xiàn)在的前端開發(fā)中牛柒,不管使用什么框架,路由的都無疑是一個必不可少的組成部分痊乾,下面我將用nodeJs的http-server來仿express框架寫一個簡易的路由皮壁。talk is cheap show me the code
路由
// router.js
const url = require('url')
// 閉包 變量私有化
const server = () => {
let G = {}
// 分別定義get和post的對象,使之無法相互影響
G._get = {}
G._post = {}
let app = function(req, res) {
// 獲取路由
const pathName = url.parse(req.url).pathname
// 獲取請求方式
const method = req.method.toLowerCase()
if (G['_' + method][pathName]) {
if (method === 'get') {
G._get[pathName](req, res) // 執(zhí)行方法
} else if (method === 'post') {
// 獲取post請求的參數(shù)
let postDate = ''
// data是分片的
req.on('data', (chunk) => {
postDate += chunk
})
req.on('end', () => {
req.body = postDate
G._post[pathName](req, res)
})
}
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('頁面不存在');
}
}
// 定義get請求方法
app.get = function (str, cb) {
// 注冊方法
G._get[str] = cb
}
// 定義post請求方法
app.post = function (str, cb) {
// 注冊方法
G._post[str] = cb
}
return app
}
module.exports = server()
服務(wù)
// express-router.js
const http = require('http');
const router = require('./module/router')
// Embedded JavaScript templates
const ejs = require('ejs')
// 注冊web服務(wù)
http.createServer(router).listen(8889);
console.log('Server running at http://127.0.0.1:8889/');
// 注冊路由
router.get('/login', function(req, res){
ejs.renderFile('./views/login.html', {}, (err, data)=> {
res.writeHead(200, {'Content-Type': 'text/html;charset="utf-8"'});
res.end(data);
})
})
router.get('/news', function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('新聞界面');
})
router.get('/regiter', function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('注冊界面');
})
router.post('/submit', function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(req.body);
})
這里的ejs是一種JavaScript模板,可參考https://www.npmjs.com/package/ejs
成品截圖
登錄
image.png
提交后
image.png