如何在节点js中转发http请求

时间:2015-12-09 10:32:51

标签: node.js http pipe

我想接受请求,将其转发到另一个网址并返回forwared请求的结果。

这是我的代码:

const http = require('http'),
      server = http.createServer().listen(3000);

const baseUrl = 'foo.bar';

server.on('request', (req, res) => {
    req.headers.host = baseUrl;

    var connector = http.request(req, (resp) => {
        resp.pipe(res);
    });

    req.pipe(connector);
});

可悲的是,我收到一个错误,就是插座挂断了。

Error: socket hang up
    at createHangUpError (_http_client.js:203:15)
    at Socket.socketOnEnd (_http_client.js:288:23)
    at emitNone (events.js:72:20)
    at Socket.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:903:12)
    at doNTCallback2 (node.js:439:9)
    at process._tickCallback (node.js:353:17)

有谁知道,我做错了什么?

1 个答案:

答案 0 :(得分:9)

尝试手动配置新请求对象,不要更改req对象。

这有效:

const http = require('http'),
    server = http.createServer().listen(3000);

const baseUrl = 'www.i.ua';

server.on('request', (req, res) => {
  var connector = http.request({
    host: baseUrl,
    path:'/',
    method: 'GET',
    headers: req.headers
  }, (resp) => {
    resp.pipe(res);
  });

  req.pipe(connector);
});

所以,你应该有这样的东西:

const http = require('http'),
    server = http.createServer().listen(3000);

const baseUrl = 'radio.i.ua';

server.on('request', (req, res) => {
  var connector = http.request({
    host: baseUrl,
    path: req.url,
    method: req.method,
    headers: req.headers
  }, (resp) => {
    resp.pipe(res);
  });

  req.pipe(connector);
});