I'm having a frustrating time trying to understand as to why the code I have provided below is not working as I expected it to. The basic concepts is:
Browser -> Nodejs Server -> MySQL Callback -> Request -> Server Response.
Would someone be able to explain as to why the following code works as expected.
// 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);
However, the moment I place the request and pipe within a callback, whether that's in a MySQL query callback (as follows) or in another request callback, it fails to pipe the response to the server.
// 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);
Your thoughts and knowledge are most welcome and thank you in advance.
Because the query to mysql is asynchronous and while the time is finished the request has finished emitting all data. You will need to pause the request until the callback is finished.
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!