Reputation: 417
I need to use the node-http-proxy library to proxy to a host with the variable target DEPENDING on the data received in the req, let's suppose that I need to find a tag and basing on this tag route to a host. My code is:
var http = require('http'),
httpProxy = require('http-proxy'),
proxy = httpProxy.createProxyServer({});
var miTarget='web:CountryName';
var inicio = '<'+miTarget+'>';
var fin = '</'+miTarget+'>';
var server = http.createServer(function(req, res) {
var miTag = '';
req.on('data', function (data) {
miTag = data.toString().split(inicio)[1].split(fin)[0];
});
req.on('end', function () {
console.log('miTag!!!!!!:'+miTag);
if(miTag=='Portugal') {
proxy.web(req, res, {target: 'http://www.webservicex.net'});
}
else {
proxy.web(req, res, {target: 'http://localhost:1337'});
}
});
});
console.log("listening on port 80")
server.listen(80);
This code is not working... Can anyone help me to sort out this problem? The most important for me is to execute thie proxy.web() AFTER the data is received miTag in the req: req.on('data', function (data) {}
Upvotes: 2
Views: 808
Reputation: 4943
I did something similar once for a little personal project. You can use res.locals as a safe place to store per-request context (much safer than using a global).
app.use('/proxy', function(req, res, next) {
// Do whatever you need to do to create targetUrl (a URL object)
var targetUrl = whatever(req);
// Save the targetUrl path so we can access it in the proxyReq handler
res.locals.path = targetUrl.path;
// Initiate the proxy
var options = {
prependPath: false,
target: targetUrl.format(),
changeOrigin: true,
hostRewrite: targetUrl.host,
protocolRewrite: targetUrl.protocol.replace(/:$/, '')
};
proxy.web(req, res, options);
});
Then setup a proxyReq handler that uses the saved targetUrl path.
proxy.on('proxyReq', function(proxyReq, req, res, options) {
if (res.locals.path) {
proxyReq.path = res.locals.path;
}
});
Upvotes: 1