From 61c0cb5c697bcd84c2f7255bfe158619694fb73d Mon Sep 17 00:00:00 2001 From: Carlos David Aguilar Ruiz Date: Mon, 19 Jun 2017 17:11:38 -0500 Subject: [PATCH] fix: Honor port for redirect (#1363) * Allow for custom port on options object in redirect --- lib/response.js | 5 ++++ test/response.test.js | 56 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/lib/response.js b/lib/response.js index eea0716f0..bde681530 100644 --- a/lib/response.js +++ b/lib/response.js @@ -640,6 +640,11 @@ Response.prototype.redirect = function redirect(arg1, arg2, arg3) { finalUri.pathname = opt.pathname; } + // then set port + if (opt.port) { + finalUri.port = opt.port; + } + // then add query params if (opt.query) { if (opt.overrideQuery === true) { diff --git a/test/response.test.js b/test/response.test.js index 0b0de1ad1..6839472c7 100644 --- a/test/response.test.js +++ b/test/response.test.js @@ -287,6 +287,62 @@ test('redirect using options.url', function (t) { }); +test('redirect using opts.port', function (t) { + SERVER.get('/9', function (req, res, next) { + res.redirect({ + port: 3000 + }, next); + }); + + CLIENT.get(join(LOCALHOST, '/9'), function (err, _, res) { + t.ifError(err); + t.equal(res.statusCode, 302); + var parsedUrl = url.parse(res.headers.location, true); + t.equal(parsedUrl.port, 3000); + t.end(); + }); +}); + + +test('redirect using external url and custom port', function (t) { + SERVER.get('/9', function (req, res, next) { + res.redirect({ + hostname: 'www.foo.com', + pathname: '/99', + port: 3000 + }, next); + }); + + CLIENT.get(join(LOCALHOST, '/9'), function (err, _, res) { + t.ifError(err); + t.equal(res.statusCode, 302); + var parsedUrl = url.parse(res.headers.location, true); + t.equal(parsedUrl.port, 3000); + t.equal(parsedUrl.hostname, 'www.foo.com'); + t.equal(parsedUrl.pathname, '/99'); + t.end(); + }); +}); + +test('redirect using default hostname with custom port', function (t) { + SERVER.get('/9', function (req, res, next) { + res.redirect({ + pathname: '/99', + port: 3000 + }, next); + }); + + CLIENT.get(join(LOCALHOST, '/9'), function (err, _, res) { + t.ifError(err); + t.equal(res.statusCode, 302); + var parsedUrl = url.parse(res.headers.location, true); + t.equal(parsedUrl.port, 3000); + t.equal(parsedUrl.pathname, '/99'); + t.equal(res.headers.location, 'http://127.0.0.1:3000/99'); + t.end(); + }); +}); + // jscs:disable maximumLineLength test('redirect should cause InternalError when invoked without next', function (t) {