Use proxyRequest event instead of subst. writeHead

Makes the code less dependent on implementation details.
This commit is contained in:
Rob Wu
2013-08-28 11:49:39 +02:00
parent 9410ff5afa
commit 198e927baa

View File

@@ -74,41 +74,27 @@ function proxyRequest(req, res, proxy, full_url, isRequestedOverHttps, proxyOpti
// Let the "Host" header be the host part of the path (including port, if specified).
req.headers.host = full_url.split('/', 3)[2];
// Hook res.writeHead
var res_writeHead = res.writeHead;
res.writeHead = function(statusCode, reasonPhrase, headers) {
if (typeof reasonPhrase === 'object') {
headers = reasonPhrase;
reasonPhrase = undefined;
}
headers = withCORS(headers || {}, req);
withCORS(headers, req);
// "Allow observer to modify headers or abort response"
// https://github.com/nodejitsu/node-http-proxy/blob/ebbba73e/lib/node-http-proxy/http-proxy.js#L321-L322
proxy.on('proxyResponse', function(req, res, response) {
withCORS(response.headers, req);
var statusCode = response.statusCode;
// Handle redirects
if (statusCode === 301 || statusCode === 302 || statusCode === 303 || statusCode === 307 || statusCode === 308) {
var locationHeader = headers['location'] || res.getHeader('location');
var locationHeader = response.headers['location'];
if (locationHeader) {
res.removeHeader('location');
headers['location'] = (isRequestedOverHttps ? 'https://' : 'http://') + realHost + '/' +
url.resolve(full_url, locationHeader);
response.headers['location'] = (isRequestedOverHttps ? 'https://' : 'http://') + realHost + '/' +
url.resolve(full_url, locationHeader);
}
}
// Don't slip through cookies
delete headers['set-cookie'];
delete headers['set-cookie2'];
res.removeHeader('set-cookie');
res.removeHeader('set-cookie2');
delete response.headers['set-cookie'];
delete response.headers['set-cookie2'];
headers['x-request-url'] = full_url;
if (reasonPhrase) {
return res_writeHead.call(res, statusCode, reasonPhrase, headers);
} else {
return res_writeHead.call(res, statusCode, headers);
}
};
response.headers['x-request-url'] = full_url;
});
// Start proxying the request
proxy.proxyRequest(req, res, proxyOptions);