Skip to content

Commit ebd795c

Browse files
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 http-party#930, http-party#1168, http-party#908
1 parent c979ba9 commit ebd795c

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

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

+13-7
Original file line numberDiff line numberDiff line change
@@ -162,16 +162,22 @@ module.exports = {
162162

163163
proxyReq.on('response', function(proxyRes) {
164164
if(server) { server.emit('proxyRes', proxyRes, req, res); }
165-
for(var i=0; i < web_o.length; i++) {
166-
if(web_o[i](req, res, proxyRes, options)) { break; }
165+
if (!res.headersSent) {
166+
for(var i=0; i < web_o.length; i++) {
167+
if(web_o[i](req, res, proxyRes, options)) { break; }
168+
}
167169
}
168170

169171
// Allow us to listen when the proxy has completed
170-
proxyRes.on('end', function () {
171-
server.emit('end', req, res, proxyRes);
172-
});
173-
174-
proxyRes.pipe(res);
172+
if (!res.finished) {
173+
proxyRes.on('end', function () {
174+
server.emit('end', req, res, proxyRes);
175+
});
176+
proxyRes.pipe(res);
177+
}
178+
else {
179+
server.emit('end', req, res, proxyRes);
180+
}
175181
});
176182

177183
//proxyReq.end();

0 commit comments

Comments
 (0)