node.js搭建動態伺服器

一杯清泉發表於2020-10-12

//引入相關模組
let http = require('http');
let path = require('path');
let url = require('url');
let fs = require('fs');

//新增靜態自願程式碼,詳情看上一節
function staticRoot(staticPath, req, res) {

    let pathObj = url.parse(req.url, true);
    if (pathObj.pathname === '/favicon.ico') {
        return;
    }
    if (pathObj.pathname === '/') {
        pathObj.pathname += 'index.html';
    }
    let filePath = path.join(staticPath, pathObj.pathname);
    fs.readFile(filePath, 'binary', (err, data) => {
        if (err) {
            res.writeHead(404, 'not found');
            res.write('<h1>Not Found</h1>')
            res.end()
        } else {
            res.writeHead(200, 'ok')
            res.write(data, 'binary');
            res.end()
        }
    })
}

//介面程式碼
var routes = {
    '/a': function(req, res){
        res.end(JSON.stringify(req.query))
    },

    '/b': function(req, res){
        res.end('match /b')
    },

    '/a/c': function(req, res){
        res.end('match /a/c')
    },

    '/search': function(req, res){
        res.end('username='+req.body.username+',password='+req.body.password)
    }
}

//解析請求資源
function routePath(req, res) {
    //解析請求的url
    let pathObj = url.parse(req.url, true);
    //獲取引數名稱,返回函式物件
    let handleFunc = routes[pathObj.pathname];
    //判斷routes陣列中存在介面資料
    if (handleFunc) {
        //存在,監聽data和on事件
        let body = '';
        req.on('data', function (chunk) {
            //獲取載入的資料
            body += chunk;
            console.log(body)
        }).on('end', function () {
            //載入完成,解析body
            req.body = parseBody(body);
            //傳遞引數,呼叫引數物件
            handleFunc(req, res)
        })
    } else {
        //不存在,則是靜態資源
        staticRoot(path.join(__dirname, 'static'), req, res)
    }
}

//解析body引數,簡單的處理
function parseBody(body){
    console.log(body)
    var obj = {}
    body.split('&').forEach(function(str){
        obj[str.split('=')[0]] = str.split('=')[1]
    })
    return obj
}

//建立服務
http.createServer((req, res) => {
    routePath(req, res);
}).listen(8080)

 

相關文章