Created
July 15, 2014 03:29
-
-
Save steel1990/77fd5d266bbe92e84f71 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require("http"), | |
urlHandler = require("url"); | |
http.createServer(function (request, response) { | |
console.log(request.url); | |
var options = {}; | |
//请求前处理 | |
var url = urlHandler.parse(handlerUrl(request.url)); | |
options.host = url.host; | |
options.hostname = url.hostname; | |
options.port = url.port; | |
options.method = request.method; | |
options.path = url.path; | |
options.headers = request.headers; | |
var postData = ''; | |
request.on("data", function(chunk){ | |
postData += chunk; | |
console.log("post data is :" + postData); | |
}); | |
request.on("end", function(){ | |
console.log("post end, data is:" + postData); | |
//转发请求 | |
var req = http.request(options, function(res){ | |
console.log(res.statusCode); | |
response.writeHead(res.statusCode, res.headers); | |
var data = ''; | |
res.on("data", function(chunk){ | |
data += chunk; | |
response.write(chunk); | |
}).on("end", function(){ | |
//处理返回结果 | |
handlerResponse(url, res.statusCode, res.headers, data); | |
response.end(); | |
}).on("error", function(e){ | |
console.log("problem width response: " + e.message); | |
}); | |
}); | |
req.on('error', function(e) { | |
console.log('problem with request: ' + e.message); | |
}); | |
req.write(postData); | |
req.end(); | |
}); | |
// response.end("xx"); | |
}).listen(3128); | |
console.log("proxy start at 3128"); | |
function handlerUrl(url){ | |
// url = url.replace(/http:\/\/mobads\.baidu\.com\/ads\/js\/exp\.js/, "http://172.17.234.116:8099/exp.js"); | |
if(url === 'http://mobads.baidu.com/ads/js/exp.js'){ | |
url = 'http://172.17.234.92:8099/exp.js'; | |
} | |
console.log(url); | |
return url; | |
} | |
function handlerResponse(url, statusCode, headers, data){ | |
//do something | |
// console.log(url, data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment