From c6114848cbdc9f9b32d61044ec1dee3434d799a0 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 | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/lib/http-proxy/passes/web-incoming.js b/lib/http-proxy/passes/web-incoming.js index 419a5dfb6..e8521d671 100644 --- a/lib/http-proxy/passes/web-incoming.js +++ b/lib/http-proxy/passes/web-incoming.js @@ -170,21 +170,23 @@ module.exports = { proxyReq.on('response', function(proxyRes) { if(server) { server.emit('proxyRes', proxyRes, req, res); } - // Allow us to listen when the proxy has completed - proxyRes.on('end', function () { - server.emit('end', req, res, proxyRes); - }); - - if(!options.selfHandleResponse) { + if(!res.headersSent && !options.selfHandleResponse) { for(var i=0; i < web_o.length; i++) { if(web_o[i](req, res, proxyRes, options)) { break; } } - - proxyRes.pipe(res); } - }); - //proxyReq.end(); + if (!res.finished) { + // Allow us to listen when the proxy has completed + proxyRes.on('end', function () { + if (server) server.emit('end', req, res, proxyRes); + }); + // We do this separately since we are also checking for res.finished + if (!options.selfHandleResponse) proxyRes.pipe(res); + } else { + if (server) server.emit('end', req, res, proxyRes); + } + }); } };