Request within a request callback not behaving as expected (nodejs)

I started playing with nodejs yesterday afternoon. This morning I started writing a proxy server and have the following requirements once a request has been received:

  • Perform auth check (through request())
  • If auth check evaluates to true, do actual request (proxy)
  • Else, redirect

All works correctly bar the actual proxy request (assigned to proxy var). It either is not being called, or at least, the response is not being pipped back to the request. Or something else, which I feel could be to do with the asynchronous behavior of nodejs.

Additional note: "Win!" is output on the console.

Any thoughts are welcomed.

var server = httpProxy.createServer(function(request, response, proxy) {
  var requestHostname = request.headers['x-forwarded-host'];
  var configFile      = './config/'+requestHostname+'.js';

  if(path.existsSync(configFile))
  {
    var config  = require(configFile);

    var authProxy = requester({
      url:    config.proxyRequest.url+config.proxyRequest.defaultPath,
      port:   443,
      method: request.method
    }, function(error, proxyResp, body) {       
      if(config.methods.authCheck(body)) 
      {
        console.log('Win!');

        proxy = requester({
          url:    'http://www.google.com',
          port:   443,
          method: request.method
        });

        // Pipe request and response back
        request.pipe(proxy);
        proxy.pipe(response);
      }
      else
      {
        response.writeHead(300, 'Forbidden', {
          'Location': globalConf.portalUrl
        });

        response.end();
      }
    });
  }
  else
  {
    response.writeHeader(400);
    response.write('404: The requested URL '+requestHostname+' does not exist.');
    response.end();
  }

  response.addListener('end', function() {
    console.log('Ending it');
  })
});

The problem is that you are assigning a return value to authProxy and proxy. You should call requester without assigning a value, just:

requester( object, callback );

I'm not sure what requester returns in your code, but when calling async functions, you don't typically expect a return value, handle everything else in the callback passed as parameter. Maybe if you add a sample of that code (requester function), things will be clearer :)