diff --git a/lib/_http_client.js b/lib/_http_client.js index 73d7b84c17a8fd..4729e87393f0a1 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -375,18 +375,22 @@ function ClientRequest(input, options, cb) { if (host && !this.getHeader('host') && setHost) { let hostHeader = host; - // For the Host header, ensure that IPv6 addresses are enclosed - // in square brackets, as defined by URI formatting - // https://tools.ietf.org/html/rfc3986#section-3.2.2 - const posColon = hostHeader.indexOf(':'); - if (posColon !== -1 && - hostHeader.includes(':', posColon + 1) && - hostHeader.charCodeAt(0) !== 91/* '[' */) { - hostHeader = `[${hostHeader}]`; - } + if (method === 'CONNECT' && options.path) { + hostHeader = String(this.path); + } else { + // For the Host header, ensure that IPv6 addresses are enclosed + // in square brackets, as defined by URI formatting + // https://tools.ietf.org/html/rfc3986#section-3.2.2 + const posColon = hostHeader.indexOf(':'); + if (posColon !== -1 && + hostHeader.includes(':', posColon + 1) && + hostHeader.charCodeAt(0) !== 91/* '[' */) { + hostHeader = `[${hostHeader}]`; + } - if (port && +port !== defaultPort) { - hostHeader += ':' + port; + if (port && +port !== defaultPort) { + hostHeader += ':' + port; + } } this.setHeader('Host', hostHeader); } diff --git a/test/parallel/test-http-connect-default-host-header.js b/test/parallel/test-http-connect-default-host-header.js new file mode 100644 index 00000000000000..9522f028f5165b --- /dev/null +++ b/test/parallel/test-http-connect-default-host-header.js @@ -0,0 +1,37 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); + +const target = 'target.example.com:443'; + +const server = net.createServer(common.mustCall((socket) => { + socket.once('data', common.mustCall((data) => { + const rawRequest = data.toString(); + const requestLines = rawRequest.split('\r\n'); + + assert.strictEqual(requestLines[0], `CONNECT ${target} HTTP/1.1`); + assert(requestLines.includes(`Host: ${target}`)); + + socket.end('HTTP/1.1 200 Connection established\r\n\r\n'); + })); +})); + +server.listen(0, common.localhostIPv4, common.mustCall(() => { + const req = http.request({ + host: common.localhostIPv4, + port: server.address().port, + method: 'CONNECT', + path: target, + }, common.mustNotCall()); + + req.on('connect', common.mustCall((res, socket) => { + assert.strictEqual(res.statusCode, 200); + socket.destroy(); + server.close(); + })); + + req.end(); +}));