Node.js學(xué)習(xí)——封裝Express的app.get()栈妆、app.post()方法

封裝一個Express的app.get()

新建一個項目文件,新建/modules/routers.js

const url = require('url');
let methods = {};

let app = function(req,res){
    let pathName = url.parse(req.url).pathname;
    if(methods[pathName]){
        methods[pathName](req,res)
    }else{
        res.writeHead(404, {
            "Content-Type": "text/html;charset=UTF-8"
        });
        res.end('頁面不存在');
    }
}

app.get = function(pathName, cd){
    methods[pathName] = cd;
}

module.exports = app;

使用上述封裝的方法馒稍,新建/app.js

const http = require('http');
const app = require('./modules/routers')

http.createServer(app).listen(3000);

app.get('/login',(req,res)=>{
    res.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });
    res.end('訪問登錄界面');
})
app.get('/news',(req,res)=>{
    res.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });
    res.end('訪問新聞界面');
})
app.get('/register',(req,res)=>{
    res.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });
    res.end('訪問注冊界面');
})

此時瀏覽器地址欄中輸入
http://127.0.0.1:3000/login
頁面內(nèi)容為:訪問登錄界面
輸入
http://127.0.0.1:3000/xxx
頁面內(nèi)容為:頁面不存在

封裝POST方法

app.js中

const http = require('http');
const path = require('path');
const app = require('./modules/routers')

const ejs = require('ejs');

http.createServer(app).listen(3000);

app.get('/login',(req,res)=>{
    ejs.renderFile(path.join(__dirname,'./views/form.ejs'),(err,data)=>{
        res.send(data);
    })
})
app.post('/doLogin',(req,res)=>{
    res.send(req.body);
})
app.get('/news',(req,res)=>{
    res.send();
})
app.get('/register',(req,res)=>{
    res.send('訪問注冊界面');
})

/modules/router.js

const fs = require('fs');
const path = require('path');
const url = require('url');
// 封裝 res.writeHead和res.end
function changeRes(req, res) {
    res['send'] = (str) => {
        res.writeHead(200, {
            "Content-Type": "text/html;charset=UTF-8"
        });
        res.end(str);
    }
}

let server = () => {
    let methods = {
        _get: {},
        _post: {},
    };
    let app = function (req, res) {
        changeRes(req, res);
        let pathName = url.parse(req.url).pathname;
        let method = req.method.toLowerCase();
        let extname = path.extname(pathName); // 獲取后綴名华匾,如果有后綴名走的是靜態(tài)web映琳,如果沒有后綴名就走的是路由
        if (!extname) {
            switch (method) {
                case 'get':
                    methods["_" + method][pathName](req, res)
                    break;
                case 'post':  // 新增封裝的post請求
                    let postData = '';
                    req.on('data', (chunk) => {
                        postData += chunk
                    })
                    req.on('end', () => {
                        req.body = postData;
                        methods["_" + method][pathName](req, res)
                    })
                    break;

                default:
                    res.writeHead(404, {
                        "Content-Type": "text/html;charset=UTF-8"
                    });
                    res.end('頁面不存在');
                    break;
            }
        }
    }

    app.get = function (pathName, cd) {
        methods._get[pathName] = cd;
    }
    app.post = function (pathName, cd) {
        methods._post[pathName] = cd;
    }
    return app;
}
module.exports = server();

封裝訪問靜態(tài)web

app.js

const http = require('http');
const path = require('path');
const app = require('./modules/routers')

const ejs = require('ejs');

http.createServer(app).listen(3000);

app.static('./static');  // 訪問靜態(tài)web文件static

app.get('/login',(req,res)=>{
    ejs.renderFile(path.join(__dirname,'./views/form.ejs'),(err,data)=>{
        res.send(data);
    })
})
app.post('/doLogin',(req,res)=>{
    res.send(req.body);
})
app.get('/news',(req,res)=>{
    res.send();
})
app.get('/register',(req,res)=>{
    res.send('訪問注冊界面');
})

modules/routers.js中

const fs = require('fs');
const path = require('path');
const url = require('url');

function changeRes(req, res) {
    res['send'] = (str) => {
        res.writeHead(200, {
            "Content-Type": "text/html;charset=UTF-8"
        });
        res.end(str);
    }
}
// 靜態(tài)web
function getFileMime(extraname) {
    let data = fs.readFileSync(path.join(__dirname, '../data/mime.json'));
    data = JSON.parse(data.toString())
    return data[extraname]
}
// 訪問靜態(tài)web的方法
function initStatic(req, res, staticPath) {
    let pathName = req.url; // 獲取到請求的url
    pathName = url.parse(pathName).pathname; // 使用url內(nèi)置模塊獲取路徑名
    let extname = path.extname(pathName); // 使用內(nèi)容模塊path獲取文件后綴名        
    try {
        let data = fs.readFileSync(staticPath + pathName);
        if (data) {
            let mime = getFileMime(extname); // 使用自定義模塊根據(jù)后綴名獲取Content-Type的值    
            res.writeHead(200, {
                "Content-Type": "" + mime + ";charset=UTF-8"
            });
            res.end(data);
        }
    } catch (error) {
    }
}

let server = () => {
    let methods = {
        _get: {},
        _post: {},
        staticPathName: '../static'  // 默認靜態(tài)文件目錄
    };

    let app = function (req, res) {
        changeRes(req, res);
        initStatic(req, res, methods.staticPathName);  // 執(zhí)行訪問靜態(tài)web函數(shù)
        let pathName = url.parse(req.url).pathname;
        let method = req.method.toLowerCase();
        let extname = path.extname(pathName); // 獲取后綴名,如果有后綴名走的是靜態(tài)web瘦真,如果沒有后綴名就走的是路由
        if (!extname) {
            switch (method) {
                case 'get':
                    methods["_" + method][pathName](req, res)
                    break;

                case 'post':
                    let postData = '';
                    req.on('data', (chunk) => {
                        postData += chunk
                    })
                    req.on('end', () => {
                        req.body = postData;
                        methods["_" + method][pathName](req, res)
                    })
                    break;

                default:
                    res.writeHead(404, {
                        "Content-Type": "text/html;charset=UTF-8"
                    });
                    res.end('頁面不存在');
                    break;
            }
        }

    }

    app.get = function (pathName, cd) {
        methods._get[pathName] = cd;
    }
    app.post = function (pathName, cd) {
        methods._post[pathName] = cd;
    }
    app.static = function (staticPath) {
        methods.staticPathName = staticPath;
    }
    return app;
}
module.exports = server();
let data = fs.readFileSync(path.join(__dirname, '../data/mime.json'));

引入完整的對應(yīng)關(guān)系需要使用一個json文件:https://github.com/wxyzcctv/node-demo-sd10/blob/main/data/mime.json
該json文件放在/data/mime.json

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末刊头,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子诸尽,更是在濱河造成了極大的恐慌原杂,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件您机,死亡現(xiàn)場離奇詭異穿肄,居然都是意外死亡,警方通過查閱死者的電腦和手機际看,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進店門咸产,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人仲闽,你說我怎么就攤上這事脑溢。” “怎么了赖欣?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵屑彻,是天一觀的道長。 經(jīng)常有香客問我顶吮,道長社牲,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任悴了,我火速辦了婚禮搏恤,結(jié)果婚禮上违寿,老公的妹妹穿的比我還像新娘。我一直安慰自己熟空,他們只是感情好藤巢,可當我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著痛阻,像睡著了一般菌瘪。 火紅的嫁衣襯著肌膚如雪腮敌。 梳的紋絲不亂的頭發(fā)上阱当,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天,我揣著相機與錄音糜工,去河邊找鬼弊添。 笑死,一個胖子當著我的面吹牛捌木,可吹牛的內(nèi)容都是我干的油坝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼刨裆,長吁一口氣:“原來是場噩夢啊……” “哼澈圈!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起帆啃,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤瞬女,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后努潘,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體诽偷,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年疯坤,在試婚紗的時候發(fā)現(xiàn)自己被綠了报慕。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡压怠,死狀恐怖眠冈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情菌瘫,我是刑警寧澤蜗顽,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站突梦,受9級特大地震影響诫舅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜宫患,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一刊懈、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦虚汛、人聲如沸匾浪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蛋辈。三九已至,卻和暖如春将谊,著一層夾襖步出監(jiān)牢的瞬間冷溶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工尊浓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留逞频,地道東北人。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓栋齿,卻偏偏與公主長得像苗胀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子瓦堵,可洞房花燭夜當晚...
    茶點故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容