在MySQL回调中管理`request`响应服务器响应不能按预期工作?的NodeJS

时间:2013-01-10 15:54:25

标签: mysql node.js http callback request

我有一个令人沮丧的时间试图理解为什么我在下面提供的代码没有像我预期的那样工作。基本概念是:

浏览器 - > Nodejs服务器 - > MySQL回调 - >请求 - >服务器响应。

是否有人能够解释为什么以下代码按预期工作。

// Load modules
var http        = require('http');
var https       = require('https');
var httpProxy   = require('http-proxy'); 
var url         = require('url');
var qstr        = require('querystring');
var path        = require('path');
var requester   = require('request');

var server = httpProxy.createServer(function(request, response) { 

    proxy = requester({
      url: 'http://www.srcnix.com',
      method: 'GET'
    });      

    request.pipe(proxy);
    proxy.pipe(response);

});

server.listen(8080);

但是,当我将请求和管道放在回调中时,无论是在MySQL查询回调中(如下所示)还是在另一个请求回调中,它都无法将响应传递给服务器。

// Load modules
var http        = require('http');
var https       = require('https');
var httpProxy   = require('http-proxy'); 
var url         = require('url');
var qstr        = require('querystring');
var path        = require('path');
var requester   = require('request');

var globalConf  = require('./config/global.js');

var mysql       = require('mysql');
var connection  = mysql.createConnection({
  host:     globalConf.db.portal.host,
  user:     globalConf.db.portal.username,
  password: globalConf.db.portal.password,
  database: globalConf.db.portal.database
});

var server = httpProxy.createServer(function(request, response) { 
  connection.query('SELECT 1', function(err, rows) {        
    if(rows.length) 
    {
      proxy = requester({
        url: 'http://www.srcnix.com',
        method: 'GET'
      });      

      // PIPE FAILS TO WORK!                
      request.pipe(proxy);
      proxy.pipe(response);
    }
  });      
});

server.listen(8080);

非常欢迎您的想法和知识,并提前感谢您。

1 个答案:

答案 0 :(得分:0)

因为对mysql的查询是异步的,并且在时间结束时,请求已完成发出所有数据。您需要暂停请求,直到回调完成。

var server = httpProxy.createServer(function(request, response) {
  request.pause();
  connection.query('SELECT 1', function(err, rows) {        
    if(rows.length) 
    {
      request.resume();
      proxy = requester({
        url: 'http://www.srcnix.com',
        method: 'GET'
      });      

      // PIPE FAILS TO WORK!                
      request.pipe(proxy);
      proxy.pipe(response);
    }
  });      
});

Have a look here, this is where i got the response from and worked for me!