http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.91k stars 1.97k forks source link

Type error in url parsing when using rewrite options and target option is an object #1338

Open tverilytt opened 5 years ago

tverilytt commented 5 years ago

Hi!

I ran into the error below when trying to use protocolRewrite (or hostRewrite).

I think the reason is I have configured the proxy options "target" as an object, e.g. target: { host: 'www.example.com', port: 443, protocol: 'https:' }

I assume that, if the options.target property is an object, the URL string version could be built from the options.target object properties...

Cheers -jo


TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type object at Url.parse (url.js:154:11) at Object.urlParse [as parse] (url.js:148:13) at Array.setRedirectHostRewrite (/Users/jo/Timegrip/gitkraken/europris-proxy/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js:54:24) at ClientRequest. (/Users/jo/Timegrip/gitkraken/europris-proxy/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:175:22) at ClientRequest.emit (events.js:189:13) at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:556:21) at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17) at TLSSocket.socketOnData (_http_client.js:442:20) at TLSSocket.emit (events.js:189:13) at addChunk (_stream_readable.js:284:12)

https://github.com/nodejitsu/node-http-proxy/blob/master/lib/http-proxy/passes/web-outgoing.js

54 var target = url.parse(options.target);

theothermattm commented 4 years ago

I am also hitting this via express-gateway issue 904. Any way around this anyone has found?

theothermattm commented 4 years ago

I was able to get around this by using the following patch file installed via patch after install of dependencies.

I will try to put up a PR with this.

diff --git a/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js b/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js
index 46352f6..d78597a 100644
--- a/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js
+++ b/node_modules/http-proxy/lib/http-proxy/passes/web-outgoing.js
@@ -51,7 +51,15 @@ module.exports = { // <--
     if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite)
         && proxyRes.headers['location']
         && redirectRegex.test(proxyRes.statusCode)) {
-      var target = url.parse(options.target);
+      var optionsTarget = options.target;
+      var target; 
+      if (optionsTarget && typeof optionsTarget === 'string' || optionsTarget instanceof String) {
+        target = url.parse(optionsTarget);
+      }
+      else {
+        target = optionsTarget
+      }
+
       var u = url.parse(proxyRes.headers['location']);

       // make sure the redirected host matches the target host before rewriting