node.js搭建动态服务器


//引入相关模块
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)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值