Routing Proxy : Dynamic Routing on basis of path
Hi,
I try to use node-http-proxy as a reverse proxy which resolves the target url to send the request to by making a lookup on the path in the request url. The path in the request url is looked up in a DB table and subsequently the target url to be used is sent to the proxy server.
E.g. http://myhost/app1 ==> http://myserver:myport/key1/app1
However I get a 404 on all the associated scripts, stylesheets which are a part of the original document returned by the server. Short of defining handlers for all paths on the hostname is there anyway i can handle this scenario. I do not want to use a hostname only based proxying approach.
var http = require('http'),
urlParser = require('url'),
httpProxy = require('./node-http-proxy/lib/node-http-proxy'),
mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'password',
database : 'routes'
});
connection.connect();
var server = httpProxy.createServer(function(req, res, proxy) {
var target={
host:'myhost.com',
port:80
};
var buffer = httpProxy.buffer(req);
var originalURL = req.url;
var appPath = urlParser.parse(req.url).pathname.substr(1);
var query = 'SELECT HOST, PROTOCOL, PATH from app_routes where NAME=';
connection.query(query + connection.escape(appPath),
function(err, rows, fields) {
if (err) throw err;
if(rows.length >=1) {
target.host = rows[0].HOST;
target.port = rows[0].PORT?rows[0].port:80;
target.changeOrigin = true;
req.url = req.url.replace(appPath, rows[0].PATH);
}
req.headers['host']= target.host;
target.buffer = buffer;
proxy.proxyRequest(req, res, target);
});
});
server.on('close', function() {
console.log('Shutting down the server');
connection.end();
});
server.listen(8000);
@baradas. What was the fix for this? Trying to do something similar...
@tybenz open a new issue if you cant figure out how to get it to work. Node automatially buffers requests for you so there is no need to do manual buffering in this case when doing an async lookup for a host. Checkout the readme for the latest API