Skip to content

Commit

Permalink
feature: Support port overrides in connect() (#1564)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
bennbollay authored Jun 28, 2020
1 parent 77bcb11 commit 7a25f3e
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 5 deletions.
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
});

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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 <tj@vision-media.ca>",
"browser": {
"./src/node/index.js": "./src/client.js",
Expand Down
20 changes: 16 additions & 4 deletions src/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down
18 changes: 18 additions & 0 deletions test/node/redirects.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];

Expand Down

0 comments on commit 7a25f3e

Please sign in to comment.