2013-01-09 110 views
0

昨天下午我开始使用nodejs。今天早上,我开始写一个代理服务器,并有以下要求一旦已接收到请求:请求回调中的请求不像预期的那样运行(nodejs)

  • (通过请求())
  • 如果身份验证检查结果为真,做实际的请求(代理进行身份验证检查)
  • 否则,重定向

所有工作正常酒吧的实际代理请求(分配给代理变量)。它要么没有被调用,要么至少没有被回复到请求中。还有其他的东西,我觉得可能与nodejs的异步行为有关。

附加说明:“Win!”在控制台上输出。

欢迎任何想法。

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'); 
    }) 
}); 

回答

0

的问题是,你是authProxyproxy分配一个返回值。你应该叫requester而不设定值,只是:

requester(object, callback); 

我不知道是什么在你的代码requester回报,但异步调用函数时,你通常不会指望一个返回值,处理一切在callback作为参数传递。也许如果你添加该代码的示例(请求函数),事情会更清晰:)

+0

感谢您的响应randunel。请求者只是一个请求的实例,由Github上的mikeal模块化。明天早上我会给你一个建议。 – srcnix

+0

Modulw应该是模块。 – srcnix

+0

这并没有解决这个问题,因为我需要'proxy'返回值来管道结果。然而,我不需要'authProxy',因为没有任何东西被返回。 – srcnix