Unhandled stream error in pipe in Node.js

Vladislav picture Vladislav · Apr 16, 2016 · Viewed 7.9k times · Source

I use local proxy in Node.js and Express with the following code:

app.post('/', function(req, res){
  var newurl =  req.body.url;
  var options = {
    url: newurl,
    headers: {
     'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
     'Accept-Language':'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
     'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
    }
  };
  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Access-Control-Allow-Origin' : '*'});
  try {
    request(options).pipe(res);
  } catch (err) {
    res.write(err.message);
    res.end();
  }
});

It works fine for the majority of the websites, but when I try to retrieve pages from some of the websites, Node throws the following error:

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^

Error: socket hang up
    at createHangUpError (_http_client.js:200:15)
    at Socket.socketOnEnd (_http_client.js:285:23)
    at emitNone (events.js:72:20)
    at Socket.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:905:12)
    at nextTickCallbackWith2Args (node.js:437:9)
    at process._tickCallback (node.js:351:17)

It doesn't occur every time for any given page, but rather from time to time. So even after some research on the internet I can't figure out how to solve that problem.

Answer

Sarath Ak picture Sarath Ak · Jul 18, 2018

This is how i solved the problem. removed try-cache and add error event

request({...}).on('error', error => {
res.status(502).send(error.message);
});