使用带有请求包和功能pipe

使用带有请求包和功能pipe

本文介绍了使用带有请求包和功能pipe()的Node.js服务器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我正在使用Node.js服务器来模拟后端.该服务器是一个网络服务器,并在不同的请求上返回json对象,工作完美无缺.现在,我必须从另一个域获取json对象,因此必须代理服务器.我在npm中找到了一个名为 request 的软件包.我可以使用简单的示例来工作,但必须转发整个网页.

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.

我的代理代码如下:

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

我正在登录真实服务器,并且它运行正常,可以跟踪get响应,但是主体为空.我只想通过request.pipe函数从nodejs服务器浏览整个网站.有什么想法吗?

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?

推荐答案

由于在Node.js中,a.pipe(b)返回b(请参见文档),您的代码与此等效:

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);

由于您只希望使用代理,因此无需将req通过管道传递到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);

这篇关于使用带有请求包和功能pipe()的Node.js服务器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 23:14