From ebd795cd9dd02a43cfada3a5cb4a958f84235627 Mon Sep 17 00:00:00 2001 From: Thiago Bustamante Date: Fri, 26 May 2017 11:05:29 -0300 Subject: [PATCH] Fix "Can't set headers after they are sent" errors This PR tries to fix "Can't set headers after they are sent" errors. That are a lot of situations where this error can occurs. In my case, it is happening because I have others middlewares (in an expressjs application that tries to proxy requests). Some of those middlewares (like [passportjs](http://passportjs.org/), or [cors](https://www.npmjs.com/package/cors)) can run ```res.end()``` and when the proxy receive a response, it is already finished. So, it is necessary to test if we can write on the user response when the proxy response is ready. I think it could also fix #930, #1168, #908 --- lib/http-proxy/passes/web-incoming.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/http-proxy/passes/web-incoming.js b/lib/http-proxy/passes/web-incoming.js index 5cb0b03d3..494679215 100644 --- a/lib/http-proxy/passes/web-incoming.js +++ b/lib/http-proxy/passes/web-incoming.js @@ -162,16 +162,22 @@ module.exports = { proxyReq.on('response', function(proxyRes) { if(server) { server.emit('proxyRes', proxyRes, req, res); } - for(var i=0; i < web_o.length; i++) { - if(web_o[i](req, res, proxyRes, options)) { break; } + if (!res.headersSent) { + for(var i=0; i < web_o.length; i++) { + if(web_o[i](req, res, proxyRes, options)) { break; } + } } // Allow us to listen when the proxy has completed - proxyRes.on('end', function () { - server.emit('end', req, res, proxyRes); - }); - - proxyRes.pipe(res); + if (!res.finished) { + proxyRes.on('end', function () { + server.emit('end', req, res, proxyRes); + }); + proxyRes.pipe(res); + } + else { + server.emit('end', req, res, proxyRes); + } }); //proxyReq.end();