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

封裝一個(gè)Express的app.get()

新建一個(gè)項(xiàng)目文件,新建/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('頁(yè)面不存在');
    }
}

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('訪(fǎng)問(wèn)登錄界面');
})
app.get('/news',(req,res)=>{
    res.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });
    res.end('訪(fǎng)問(wèn)新聞界面');
})
app.get('/register',(req,res)=>{
    res.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });
    res.end('訪(fǎng)問(wèn)注冊(cè)界面');
})

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

封裝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('訪(fǎng)問(wèn)注冊(cè)界面');
})

/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,如果沒(méi)有后綴名就走的是路由
        if (!extname) {
            switch (method) {
                case 'get':
                    methods["_" + method][pathName](req, res)
                    break;
                case 'post':  // 新增封裝的post請(qǐng)求
                    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('頁(yè)面不存在');
                    break;
            }
        }
    }

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

封裝訪(fǎng)問(wèn)靜態(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');  // 訪(fǎng)問(wèn)靜態(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('訪(fǎng)問(wèn)注冊(cè)界面');
})

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]
}
// 訪(fǎng)問(wèn)靜態(tài)web的方法
function initStatic(req, res, staticPath) {
    let pathName = req.url; // 獲取到請(qǐng)求的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'  // 默認(rèn)靜態(tài)文件目錄
    };

    let app = function (req, res) {
        changeRes(req, res);
        initStatic(req, res, methods.staticPathName);  // 執(zhí)行訪(fǎng)問(wèn)靜態(tài)web函數(shù)
        let pathName = url.parse(req.url).pathname;
        let method = req.method.toLowerCase();
        let extname = path.extname(pathName); // 獲取后綴名,如果有后綴名走的是靜態(tài)web,如果沒(méi)有后綴名就走的是路由
        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('頁(yè)面不存在');
                    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'));

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容