Skip to content

Commit

Permalink
Fix "Can't set headers after they are sent" errors
Browse files Browse the repository at this point in the history
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
  • Loading branch information
thiagobustamante authored May 26, 2017
1 parent c979ba9 commit ebd795c
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions lib/http-proxy/passes/web-incoming.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit ebd795c

Please sign in to comment.