我很难理解为什么我在下面提供的代码没有像我预期的那样工作。基本概念是:
浏览器 -> 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);
非常欢迎您的想法和知识,并提前感谢您。