From 7a25f3e38ecc129ad67405bc85610e9482556d8c Mon Sep 17 00:00:00 2001 From: Benn Bollay Date: Sat, 27 Jun 2020 20:20:57 -0700 Subject: [PATCH] feature: Support port overrides in connect() (#1564) * Support port overrides in connect() Allow for .connect({'*': {host: 'hostname', port: 12345}}) overrides to change the destination port of a request. * Increment version to 5.2.3 --- docs/index.md | 1 + package.json | 2 +- src/node/index.js | 20 ++++++++++++++++---- test/node/redirects.js | 18 ++++++++++++++++++ 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/index.md b/docs/index.md index 01a61b624..90d7d0356 100644 --- a/docs/index.md +++ b/docs/index.md @@ -692,6 +692,7 @@ Because the request may be redirected, it's possible to specify multiple hostnam .connect({ "redir.example.com": "127.0.0.1", // redir.example.com:555 will use 127.0.0.1:555 "www.example.com": false, // don't override this one; use DNS as normal + "mapped.example.com": { host: "127.0.0.1", port: 8080}, // mapped.example.com:* will use 127.0.0.1:8080 "*": "proxy.example.com", // all other requests will go to this host }); diff --git a/package.json b/package.json index 0b710235a..c4c749086 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "superagent", "description": "elegant & feature rich browser / node HTTP with a fluent API", - "version": "5.2.2", + "version": "5.2.3", "author": "TJ Holowaychuk ", "browser": { "./src/node/index.js": "./src/client.js", diff --git a/src/node/index.js b/src/node/index.js index 7544986a3..cdd5b8d9b 100644 --- a/src/node/index.js +++ b/src/node/index.js @@ -730,13 +730,25 @@ Request.prototype.request = function() { this.set('host', url.host); } + let newHost; + let newPort; + + if (typeof match === 'object') { + newHost = match.host; + newPort = match.port; + } else { + newHost = match; + newPort = url.port; + } + // wrap [ipv6] - url.host = /:/.test(match) ? `[${match}]` : match; - if (url.port) { - url.host += `:${url.port}`; + url.host = /:/.test(newHost) ? `[${newHost}]` : newHost; + if (newPort) { + url.host += `:${newPort}`; + url.port = newPort; } - url.hostname = match; + url.hostname = newHost; } } diff --git a/test/node/redirects.js b/test/node/redirects.js index d510fd7ed..d3faa34a2 100644 --- a/test/node/redirects.js +++ b/test/node/redirects.js @@ -103,6 +103,24 @@ describe('request', () => { }); }); + it('should follow Location with IP:port override', () => { + const redirects = []; + const url = URL.parse(base); + return request + .get(`http://redir.example.com:9999${url.pathname}`) + .connect({ + '*': { host: url.hostname, port: url.port || 80 } + }) + .on('redirect', res => { + redirects.push(res.headers.location); + }) + .then(res => { + const arr = ['/movies', '/movies/all', '/movies/all/0']; + redirects.should.eql(arr); + res.text.should.equal('first movie page'); + }); + }); + it('should not follow on HEAD by default', () => { const redirects = [];