nodejs模块:简单http请求路由,仿express

nodejs模块:简单http请求路由模块

//http-rout.js
var url = require('url');

/**
 * 对resquest进行封装
 * 
 * @param {*} res 
 */
var packingRes = function (res) {
    var end = res.end;
    res.end = function (data, encoding, callback) {
        if (data && !(data instanceof Buffer) && (typeof data !== 'function')) {
            if (typeof data === 'object') {
                data = JSON.stringify(data);
            } else if (typeof data === 'number') {
                data = data.toString();
            }
        }

        end.call(res, data, encoding, callback);
    };

    res.send = function (data, type) {
        res.writeHead(200,
            {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'text/' + (type || 'plain') + '; charset=UTF-8'
            }
        );
        res.end(data);
    };

    res.sendImg = function (data, type, timeout) {
        res.writeHead(200,
            {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'image/' + (type || 'png'),
                'Content-Length': Buffer.byteLength(data),
                'Cache-Control': 'max-age=' + (timeout || 5184000)
            }
        );
        res.end(data);
    };

    return res;
};

/**
 * 路由规则
 */
var route = function () {
    var self = this;

    this._get = {};
    this._post = {};

    /**
     * 处理请求
     * 
     * @param {*} req 
     * @param {*} res 
     */
    var handle = function (req, res) {
        packingRes(res);

        var Url = url.parse(req.url, true);
        var pathname = Url.pathname;
        if (!pathname.endsWith('/')) {
            pathname = pathname + '/';
        }
        var query = Url.query;
        var method = req.method.toLowerCase();

        if (self['_' + method][pathname]) {
            if (method == 'post') {
                // 设置接收数据编码格式为 UTF-8
                // req.setEncoding('utf-8');
                var postData = '';
                // 数据块接收中
                req.on('data', function (postDataChunk) {
                    postData += postDataChunk;
                });
                // 数据接收完毕,执行回调函数
                req.on('end', function () {
                    try {
                        postData = JSON.parse(postData);
                    } catch (e) { }
                    req.query = postData;
                    self['_' + method][pathname](req, res);
                });
            } else {
                req.query = query;
                self['_' + method][pathname](req, res);
            }
        } else {
            res.send(method + '请求路由地址不存在:' + pathname);
        }
    };

    /**
     * 注册get请求
     */
    handle.get = function (string, callback) {
        if (!string.startsWith('/')) {
            string = '/' + string;
        }
        if (!string.endsWith('/')) {
            string = string + '/';
        }
        self._get[string] = callback;
    };

    /**
     * 注册post请求
     */
    handle.post = function (string, callback) {
        if (!string.startsWith('/')) {
            string = '/' + string;
        }
        if (!string.endsWith('/')) {
            string = string + '/';
        }
        self._post[string] = callback;
    };

    return handle;
};

module.exports = function () {
    return new route();
};

使用方式与express类似

//index.js
var route = require('./http-route.js');
var app = route();
var http = require('http');
var server = http.createServer(app);
app.get('/test', function (req, res) {
    console.log('GET',req.query);
    res.send(req.query);
});

app.post('/test', function (req, res) {
    console.log('POST', req.query);
    res.send(req.query);
});
server.listen(8080, function () {
    console.log('listen ' + server.address().port);
});
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值