1 Star 0 Fork 1

Mr.Chang/fframe

forked from chenjianjun571/fframe 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
proxy.js 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
chenjianjun571 提交于 2016-12-17 13:19 . no message
var http = require('http');
var config = require('./app/config');
// 记录日志
var log = function () {
var now = new Date().toISOString();
arguments[0] = '[' + now + '] ' + arguments[0];
console.log.apply(console, arguments);
};
// 获取请求的headers,去掉host和connection
var getHeader = function (req) {
var ret = {};
for (var i in req.headers) {
if (!/host|connection/i.test(i)) {
ret[i] = req.headers[i];
}
}
return ret;
};
// 获取请求的路径
var getPath = function (req) {
var url = req.url;
if (url.substr(0, 7).toLowerCase() === 'http://') {
var i = url.indexOf('/', 7);
if (i !== -1) {
url = url.substr(i);
}
}
return url;
};
// 代理请求
var counter = 0;
var onProxy = function (req, res) {
counter++;
var num = counter;
var opt = {
host: config.server_host,
port: config.server_port,
path: getPath(req),
method: req.method,
headers: getHeader(req)
};
log('#%d\t%s http://%s%s', num, req.method, opt.host, opt.path);
var req2 = http.request(opt, function (res2) {
res.writeHead(res2.statusCode, res2.headers);
res2.pipe(res);
res2.on('end', function () {
log('#%d\tEND', num);
});
});
if (/POST|PUT/i.test(req.method)) {
req.pipe(req2);
} else {
req2.end();
}
req2.on('error', function (err) {
log('#%d\tERROR: %s', num, err.stack);
res.end(err.stack);
});
};
module.exports = onProxy
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
NodeJS
1
https://gitee.com/MrZhang/fframe.git
git@gitee.com:MrZhang/fframe.git
MrZhang
fframe
fframe
master

搜索帮助