Nodejs 请求转发代理

var sendPromise = function (res, callback) {

    var options = {
        hostname: settings.Ip,
        port: settings.Port,
        path: '',
        method: 'GET',
        headers: res.req.headers
    };
    options.path = res.req.originalUrl;
    options.method = res.req.method;
    var body = res.req.body;


    var request = http.request(options, function (response) {
        var result = '';
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            result += chunk;
        });
        response.on('end', function () {

            callback(null, result);
        });
    });


    request.on('error', function (e) {
        callback('path:' + options.path + ';' + e, null);
    });

    if (body && options.method == 'POST') {
        var postBody = {};
        for (var k of Object.keys(body)) {
            postBody[k] = body[k];
        }
        request.write(postBody);
    }
    request.end();

}

 

posted on 2016-10-11 09:21  来碗板面  阅读(4847)  评论(0编辑  收藏  举报

导航