2013-01-10 59 views
1

我有一個令人沮喪的時間試圖瞭解爲什麼我下面提供的代碼沒有按照我的預期工作。基本概念是:在MySQL回調中響應服務器響應的請求響應不按預期方式工作? nodejs

瀏覽器 - > 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); 

你的思想和知識是最歡迎和感謝你提前。

回答

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!