如何在nodejs中获取和修改response.body?

时间:2017-07-31 06:22:59

标签: node.js express

我正在使用express并在中间件中编写此代码。我需要将请求代理到另一个newUrl,并且必须从newUrl获取响应的主体。但我不知道如何以这种方式得到它。谁能告诉我如何获得res.body?

var stream = req.pipe(request(newUrl)).pipe(res);
stream.on('finish', function() {
    // how can I get res.body from the newUrl?

    next();
});

1 个答案:

答案 0 :(得分:0)

以下是如何使用流进行代理请求的简便方法。

'use strict';

const
    stream = require('stream'),
    util = require('util'),
    http = require('http');

let Transform = stream.Transform;

// make Trasform stream
function MyProxyStream(options) {
  if (!(this instanceof MyProxyStream)) {
    return new MyProxyStream(options);
  }
  // set proxy url
  this.proxyUrl = 'http://go-to-proxy'
  Transform.call(this, options);
}
util.inherits(MyProxyStream, Transform);


// Transform stuff here
MyProxyStream.prototype._transform = function (chunk, enc, cb) {
    // send proxy request somethere -> get data
    // chunk is string cast to Object with JSON.parse(chunk)
    // request.post(this.proxyUrl, chunk)
    let data = "my proxy data";
    this.push(data);
  return cb();
};

const server = http.createServer((req, res) => {
    let transformer = new MyProxyStream({objectMode: true});
  req.setEncoding('utf8');
  req.pipe(transformer).pipe(res);
});

server.listen(1337);

希望这有帮助。