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 #930, #1168, #908
  • Loading branch information
thiagobustamante authored and jcrugzz committed Apr 19, 2018
1 parent 168c7d2 commit c611484
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions lib/http-proxy/passes/web-incoming.js
Expand Up @@ -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);
}
});
}

};

0 comments on commit c611484

Please sign in to comment.