nodejitsu/node-http-proxy — Issue #168: proxy does not work from a callback function
Author: taris
Created: 2011-12-15 15:28:34+00:00
State: open

I am trying to call "proxy.proxyRequest()" from a callback function after reading some data, but this does not work at all (or at least i can't see my mistake :) )

Try to use my code below - with the request url "http://localhost:8000/" everything is fine and the request will be routed to the target server (same script - port 9000).
But when you try to load something with the url "http://localhost:8000/no-routing" first (or save or anything that needs a callback function), the target server never receives a request, no error will be raised and the client never receives a response and stays pending.

Hope it stays an easy issue - any help is greatly appreciated :)
Cheers!

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

//
// Create a proxy server with custom application logic
//
httpProxy.createServer(function (req, res, proxy) {
//
// Put your custom server logic here
//
console.log("##### PROXY: NEW REQUEST #####");

if(req.url == '/no-routing') {
/**
* In a callback function the target server never receives a request and client keeps on "pending"
*/
fs.readdir(__dirname, function(err, files)
{
console.dir(proxy);
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9000
});
});
} else {
/**
* Without a callback function the request will be routed to target server
*/
console.dir(proxy);
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 9000
});
}
}).listen(8000);

http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
res.end();

console.log("##### TARGET: REQUEST RECEIVED #####");
}).listen(9000);

console.log("---\nProxy listens on port 8000 and routes anything to port 9000");
console.log("Without callback and problems: http://localhost:8000/");
console.log("With a callback and no routing: http://localhost:8000/no-routing\n---");
```