I want to take the a request, forward it to another url and return the result of the forwared request.
This is my code:
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);
});
Sadly, I'm getting an error, that the socket hung up.
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)
Does anyone know, what I'm doing wrong?
Try to configure new request object manually, and do not change req object.
This works:
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);
});
So, you should have something like this:
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);
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With