Nodejs實現簡單的反向代理


var http = require('http'), httpProxy = require('http-proxy');

// 新建一個代理 Proxy Server 對象
var proxy = httpProxy.createProxyServer({});

// 捕獲異常
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});

// 另外新建一個 HTTP 80 端口的服務器,也就是常規 Node 創建 HTTP 服務器的方法。
// 在每次請求中,調用 proxy.web(req, res config) 方法進行請求分發
var server = require('http').createServer(function(req, res) {
// 在這里可以自定義你的路由分發
var host = req.headers.host, ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
console.log("client ip:" + ip + ", host:" + host);

switch(host){

case 'vmcc.oa.com':
proxy.web(req, res, { target: 'http://vmcc.oa.com' });
break;
case 'vmcdn.oa.com':
proxy.web(req, res, { target: 'http://vmcdn.oa.com' });
break;
default:
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Welcome to my server!');
}
});

console.log("listening on port 80")
server.listen(80);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM