使用nodejs服务器与请求包和函数pipe()?

目前,我正在使用nodejs服务器来模拟后端。 服务器是一个networking服务器,并返回不同的请求json对象,工作无懈可击。 现在我必须从另一个域获取json对象,所以我必须代理服务器。 我在npm中find了一个名为request的包。 我可以得到一个简单的例子工作,但我必须转发整个网页。

我的代理代理如下所示:

var $express = require('express'), $http = require('http'), $request = require('request'), $url = require('url'), $path = require('path'), $util = require('util'), $mime = require('mime'); var app = $express(); app.configure(function(){ app.set('port', process.env.PORT || 9090); app.use($express.bodyParser()); app.use($express.methodOverride()); app.use('/', function(req, res){ var apiUrl = 'http://localhost:9091'; console.log(apiUrl); var url = apiUrl + req.url; req.pipe($request(url).pipe(res)); }); }); $http.createServer(app).listen(app.get('port'), function () { console.log("Express server listening on port " + app.get('port')); if (process.argv.length > 2 && process.argv.indexOf('-open') > -1) { var open = require("open"); open('http://localhost:' + app.get('port') + '/', function (error) { if (error !== null) { console.log("Unable to lauch application in browser. Please install 'Firefox' or 'Chrome'"); } }); } }) 

我login真正的服务器,它是正确行事,我可以跟踪得到的回应,但身体是空的。 我只想通过request.pipe函数从nodejs服务器传递整个网站。 有任何想法吗?

由于在Node.js中, a.pipe(b)返回b (请参阅文档 ),所以您的代码等同于:

 // req.pipe($request(url).pipe(res)) // is equivalent to $request(url).pipe(res); req.pipe(res); 

因为你只需要一个代理服务器就不需要pipe道req (在这里把多个可读stream写入一个可写的stream是没有意义的),只要保持这个,你的代理就可以工作:

 $request(url).pipe(res);