Last active
December 20, 2015 04:29
-
-
Save czy88840616/6071695 to your computer and use it in GitHub Desktop.
两种http代理方式的实现
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
/** | |
* @fileoverview simple project assets proxy | |
* @author 张挺 <[email protected]> | |
*/ | |
var fs = require('fs'), | |
path = require('path'), | |
http = require('http'), | |
https = require('https'), | |
url = require('url'), | |
httpProxy = require('http-proxy'); | |
var proxy = new httpProxy.RoutingProxy(); | |
http.createServer(function (req, res) { | |
var urlObj = url.parse(req.url, true), | |
domain = req.headers['x-forwarded-host'] | |
|| req.headers['X-Forwarded-For'] | |
|| urlObj.query.domain, | |
port = urlObj.query.port; | |
if(domain) { | |
req.headers["host"] = domain; | |
proxy.proxyRequest(req, res, { | |
host: domain, | |
port: port ? port : 80 | |
}); | |
} else { | |
res.statusCode = 404; | |
res.end(); | |
} | |
}).listen(3000); |
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
/** | |
* @fileoverview simple project assets proxy | |
* @author 张挺 <[email protected]> | |
*/ | |
var fs = require('fs'), | |
path = require('path'), | |
http = require('http'), | |
https = require('https'), | |
url = require('url'), | |
request = require('request'); | |
http.createServer(function (req, res) { | |
var urlObj = url.parse(req.url, true), | |
domain = req.headers['x-forwarded-host'] | |
|| req.headers['X-Forwarded-For'] | |
|| urlObj.query.domain, | |
port = urlObj.query.port, | |
newUrlObj = {}; | |
delete urlObj.query['domain']; | |
delete urlObj.query['port']; | |
newUrlObj.protocol = 'http'; | |
newUrlObj.hostname = domain; | |
newUrlObj.query = urlObj.query; | |
newUrlObj.auth = urlObj.auth; | |
newUrlObj.hash = urlObj.hash; | |
newUrlObj.pathname = urlObj.pathname; | |
if(port) { | |
newUrlObj.port = port; | |
} | |
if(domain) { | |
request(url.format(newUrlObj), { | |
headers: { | |
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36" | |
} | |
}, function (error, response, body) { | |
if (!error && response.statusCode == 200) { | |
res.end(body); | |
} else { | |
res.statusCode = 404; | |
res.end(); | |
} | |
}) | |
} else { | |
res.statusCode = 404; | |
res.end(); | |
} | |
}).listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
针对最新版本的node和http-proxy进行更新