diff --git a/request.js b/request.js index 9d3fc3e92..90bed4f4a 100644 --- a/request.js +++ b/request.js @@ -287,10 +287,14 @@ Request.prototype.init = function (options) { self.setHost = false if (!self.hasHeader('host')) { var hostHeaderName = self.originalHostHeaderName || 'host' - // When used with an IPv6 address, `host` will provide - // the correct bracketed format, unlike using `hostname` and - // optionally adding the `port` when necessary. self.setHeader(hostHeaderName, self.uri.host) + // Drop :port suffix from Host header if known protocol. + if (self.uri.port) { + if ((self.uri.port === '80' && self.uri.protocol === 'http:') || + (self.uri.port === '443' && self.uri.protocol === 'https:')) { + self.setHeader(hostHeaderName, self.uri.hostname) + } + } self.setHost = true } diff --git a/tests/test-headers.js b/tests/test-headers.js index b80c9b312..59faae87e 100644 --- a/tests/test-headers.js +++ b/tests/test-headers.js @@ -180,6 +180,56 @@ tape('undefined headers', function (t) { }) }) +tape('preserve port in host header if non-standard port', function (t) { + var r = request({ + url: s.url + '/headers.json' + }, function (err, res, body) { + t.equal(err, null) + t.equal(r.originalHost, 'localhost:' + s.port) + t.end() + }) +}) + +tape('strip port in host header if explicit standard port (:80) & protocol (HTTP)', function (t) { + var r = request({ + url: 'http://localhost:80/headers.json' + }, function (err, res, body) { + t.notEqual(err, null) + t.equal(r.req.socket._host, 'localhost') + t.end() + }) +}) + +tape('strip port in host header if explicit standard port (:443) & protocol (HTTPS)', function (t) { + var r = request({ + url: 'https://localhost:443/headers.json' + }, function (err, res, body) { + t.notEqual(err, null) + t.equal(r.req.socket._host, 'localhost') + t.end() + }) +}) + +tape('strip port in host header if implicit standard port & protocol (HTTP)', function (t) { + var r = request({ + url: 'http://localhost/headers.json' + }, function (err, res, body) { + t.notEqual(err, null) + t.equal(r.req.socket._host, 'localhost') + t.end() + }) +}) + +tape('strip port in host header if implicit standard port & protocol (HTTPS)', function (t) { + var r = request({ + url: 'https://localhost/headers.json' + }, function (err, res, body) { + t.notEqual(err, null) + t.equal(r.req.socket._host, 'localhost') + t.end() + }) +}) + var isExpectedHeaderCharacterError = function (headerName, err) { return err.message === 'The header content contains invalid characters' || err.message === ('Invalid character in header content ["' + headerName + '"]')