Created
February 16, 2014 14:01
-
-
Save yanxi123-com/9034648 to your computer and use it in GitHub Desktop.
通过 node-http-proxy 获取 request 和 response
This file contains hidden or 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 httpProxy = require('http-proxy'); | |
| var zlib = require('zlib'); | |
| var _ = require('underscore'); | |
| var express = require('express'); | |
| var http = require('http'); | |
| var path = require('path'); | |
| var ejs = require('ejs'); | |
| var request = require('request'); | |
| var app = express(); | |
| var proxy = httpProxy.createProxy({}); | |
| app.set('port', 5050); | |
| var proxyFun = function(req, res) { | |
| if (req.url.indexOf('www.abcdefg.com') > -1) { | |
| console.log(req.url); | |
| console.log(req.body); | |
| res.oldWrite = res.write; | |
| res.write = function(data) { | |
| zlib.unzip(data, function(err, buffer) { | |
| if (!err) { | |
| console.log(buffer.toString()); | |
| } else { | |
| console.log(data.toString()); | |
| } | |
| }); | |
| res.oldWrite(data); | |
| } | |
| } | |
| proxy.web(req, res, { | |
| target: 'http://' + req.headers.host | |
| }, function(e) { | |
| console.log('error'); | |
| //console.log(arguments); | |
| console.log(e); | |
| }); | |
| return; | |
| }; | |
| var stringify = function(data) { | |
| var result = ''; | |
| _.each(data, function(value, key) { | |
| result += (result ? '&' : '') + key + '=' + encodeURIComponent(value); | |
| }); | |
| return result; | |
| }; | |
| app.use(express.bodyParser()); | |
| app.use(require('connect-restreamer')({ | |
| stringify : stringify, | |
| })); | |
| app.use(function(req, res, next){ | |
| if (!req.body || !_.keys(req.body).length) | |
| return next(); | |
| var body = stringify(req.body); | |
| var length = Buffer.byteLength(body || '', 'utf8'); | |
| req['headers']['content-length'] = ""+length; | |
| next(); | |
| }); | |
| app.use(app.router); | |
| app.all('*', proxyFun); | |
| var server = http.createServer(app); | |
| server.listen(app.get('port'), function() { | |
| console.log('Express server listening on port ' + app.get('port')); | |
| }); | |
| var app2 = express(); | |
| app2.use(express.bodyParser()); | |
| app2.use(app2.router); | |
| app2.all('*', function(req, res){ | |
| console.log(req.body); | |
| res.send('abc'); | |
| }); | |
| var server2 = http.createServer(app2); | |
| server2.listen(5051, function() { | |
| console.log('Express server listening on port ' + 5051); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment