Using nodejs server with request package and function pipe()?

匆匆过客 提交于 2019-12-12 20:40:11

问题


I'm using a nodejs server to mockup a backend at the moment. The server is a webserver and returns json objects on different requests, works flawlessy. Now I have to get the json objects from another domain, so I have to proxy the server. I have found a package called request in npm. I can get the simple example to work, but I have to forward the whole webpage.

My code for the proxy looks like this:

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'");
      }
    });
  }
})

I'm loggin the real server and it is acting correctly, I can track the get response, but the body is empty. I just want to pass through the whole website from the nodejs server through the request.pipe function. Any ideas?


回答1:


Since in Node.js, a.pipe(b) returns b (see documentation), your code is equivalent to this:

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

As you only want a proxy there is no need to pipe req into res (and here it doesn't make sense to pipe multiple readable streams into one writable stream), just keep this and your proxy will work:

$request(url).pipe(res);


来源:https://stackoverflow.com/questions/22296571/using-nodejs-server-with-request-package-and-function-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!