Skip to content

Commit 8097ae2

Browse files
thiagobustamanteindexzero
authored andcommitted
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
1 parent abf882e commit 8097ae2

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

lib/http-proxy/passes/web-incoming.js

+12-10
Original file line numberDiff line numberDiff line change
@@ -170,21 +170,23 @@ module.exports = {
170170
proxyReq.on('response', function(proxyRes) {
171171
if(server) { server.emit('proxyRes', proxyRes, req, res); }
172172

173-
// Allow us to listen when the proxy has completed
174-
proxyRes.on('end', function () {
175-
server.emit('end', req, res, proxyRes);
176-
});
177-
178-
if(!options.selfHandleResponse) {
173+
if(!res.headersSent && !options.selfHandleResponse) {
179174
for(var i=0; i < web_o.length; i++) {
180175
if(web_o[i](req, res, proxyRes, options)) { break; }
181176
}
182-
183-
proxyRes.pipe(res);
184177
}
185-
});
186178

187-
//proxyReq.end();
179+
if (!res.finished) {
180+
// Allow us to listen when the proxy has completed
181+
proxyRes.on('end', function () {
182+
if (server) server.emit('end', req, res, proxyRes);
183+
});
184+
// We do this separately since we are also checking for res.finished
185+
if (!options.selfHandleResponse) proxyRes.pipe(res);
186+
} else {
187+
if (server) server.emit('end', req, res, proxyRes);
188+
}
189+
});
188190
}
189191

190192
};

0 commit comments

Comments
 (0)