在node-http-proxy中的中间件中调用asynchronous方法

我正在尝试在Node.js中使用node-http-proxy创build一个代理来检查请求是否在mongodb中被授权。

基本上,我为node-http-proxy创build了一个中间件模块,像这样使用:

httpProxy.createServer( require('./example-middleware')(), 9005, 'localhost' ).listen(8005) 

中间件模块所做的是使用mongojs连接到mongodb并运行查询以查看用户是否有权访问资源:

 module.exports = function(){ // Do something when first loaded! console.log("Middleware loaded!"); return function (req, res, next) { var record = extractCredentials(req); var query = -- Db query -- //Debug: log("Query result", query); db.authList.find(query).sort({ "url.len": -1 }, function(err, docs){ console.log(docs); // Return the creator for the longest matching path: if(docs.length > 0) { console.log("User confirmed!"); next(); } else { console.log("User not confirmed!"); res.writeHead(403, { 'Content-Type': 'text/plain' }); res.write('You are not allowed to access this resource...'); res.end(); } }); } } 

现在的问题是,只要我使用mongojs将asynchronous调用添加到mongodb中,代理就会挂起,并且永远不会发回响应。

澄清:在“用户未确认”一切工作正常,403返回。 在“用户确认”,但是我看到日志,但浏览器然后永远挂起,请求不代理。

现在,如果我删除callback之外的“用户确认”和next()部分,它将工作:

 module.exports = function(){ // Do something when first loaded! console.log("Middleware loaded!"); return function (req, res, next) { var record = extractCredentials(req); var query = --- query --- console.log("User confirmed!"); next(); } 

但我不能做到这一点,因为mongojs查询意味着(当然我猜)是asynchronous执行的,只有当数据库回复时,才会触发callback…

我也尝试过这个版本,而不使用中间件:

 http.createServer(function (req, res) { // run the async query here! proxy.proxyRequest(req, res, { host: 'localhost', port: 9000 }); }).listen(8001); 

但是这也没有帮助…

任何线索? 请注意,我是node.js的新手,所以我怀疑我的一个误区

find答案,其实是要求缓冲的要求:

 httpProxy.createServer(function (req, res, proxy) { // ignore favicon if (req.url === '/favicon.ico') { res.writeHead(200, { 'Content-Type': 'image/x-icon' } ); res.end(); console.log('favicon requested'); return; } var credentials = extractCredentials(req); console.log(credentials); var buffer = httpProxy.buffer(req); checkRequest(credentials, function(user){ if(user == ...) { console.log("Access granted!"); proxy.proxyRequest(req, res, { host: 'localhost', port: 9005, buffer: buffer }); } else { console.log("Access denied!"); res.writeHead(403, { "Content-Type": "text/plain" }); res.write("You are not allowed to access this resource..."); res.end(); } }); }).listen(8005); 

两个问题:

  1. 你不叫next(); 在你的sortcallback的情况下。
  2. sortcallback的第二个参数是一个Cursor ,而不是一个文档数组。 因此, docs.length > 0永远不会是真的,代码总是遵循elsepath。