1

I'm looking at this answer on how to proxy a request through nodejs. Here's the code presented:

function onRequest(client_req, client_res) {
  console.log('serve: ' + client_req.url);

  var options = { ... };

  var proxy = http.request(options, function (res) {
    client_res.writeHead(res.statusCode, res.headers) <--------- why this?
    res.pipe(client_res, {
      end: true
    });
  });

  client_req.pipe(proxy, {
    end: true
  });
}

Can anyone explain why I need to writeHead manually? My assumption is that headers will be piped from the response of the server the request is proxied to?

Max Koretskyi
  • 85,840
  • 48
  • 270
  • 414
  • Reading/Writing from the streams (in this case, piping the streams) only reads/writes the __body__, not the HTTP header. – tkausl Dec 09 '20 at 18:50
  • @tkausl, thanks, interesting, do you know why is that? I was under the impression that streams pipe all data they have, like a filereader. Any link to the documentation to read about it? – Max Koretskyi Dec 09 '20 at 18:58
  • `I was under the impression that sreams pipe all data they have` This depends on the stream. Different streams do different things. `do you know why is that?` Because you're using a HTTP library. Users of that library usually don't care about the raw header, the library reads and parses the header and passes the parsed data and the the body as a stream to your handler. – tkausl Dec 09 '20 at 19:03
  • @tkausl, _the library reads and parses the header and passes the parsed data and the the body as a stream to your handler._ - do you mean once parsed it sets the headers as properties on the object but sends the body as a stream? – Max Koretskyi Dec 11 '20 at 13:13

0 Answers0