Catch error due to invalid status code (#95)

This commit is contained in:
Rob Wu
2017-11-08 22:23:58 +01:00
parent 143eff177c
commit 4a46541da4
2 changed files with 49 additions and 1 deletions

View File

@@ -101,7 +101,18 @@ function proxyRequest(req, res, proxy) {
}
return proxyReqOn.call(this, 'response', function(proxyRes) {
if (onProxyResponse(proxy, proxyReq, proxyRes, req, res)) {
listener(proxyRes);
try {
listener(proxyRes);
} catch (err) {
// Wrap in try-catch because an error could occur:
// "RangeError: Invalid status code: 0"
// https://github.com/Rob--W/cors-anywhere/issues/95
// https://github.com/nodejitsu/node-http-proxy/issues/1080
// Forward error (will ultimately emit the 'error' event on our proxy object):
// https://github.com/nodejitsu/node-http-proxy/blob/v1.11.1/lib/http-proxy/passes/web-incoming.js#L134
proxyReq.emit('error', err);
}
}
});
};
@@ -400,6 +411,14 @@ exports.createServer = function createServer(options) {
// the headers because it would generate an error.
return;
}
// When the error occurs after setting headers but before writing the response,
// then any previously set headers must be removed.
var headerNames = res.getHeaderNames ? res.getHeaderNames() : Object.keys(res._headers);
headerNames.forEach(function(name) {
res.removeHeader(name);
});
res.writeHead(404, {'Access-Control-Allow-Origin': '*'});
res.end('Not found because of proxy error: ' + err);
});