diff --git a/lib/httpRequestBuilder.js b/lib/httpRequestBuilder.js index efd86ec4..57aa3dea 100644 --- a/lib/httpRequestBuilder.js +++ b/lib/httpRequestBuilder.js @@ -45,14 +45,21 @@ function requestBuilder (defaults) { const headers = reqData.headers const body = reqData.body - let host = getPropertyCaseInsensitive(reqData.headers, 'host') || reqData.host + const headersDefinedHost = getPropertyCaseInsensitive(reqData.headers, 'host') + let host = headersDefinedHost || reqData.host if (!host) { const hostname = reqData.hostname const port = reqData.port host = hostname + ':' + port } - + const baseReq = [ + `${method} ${path} HTTP/1.1` + ] + if (!headersDefinedHost) { + baseReq.push(`Host: ${host}`) + } + baseReq.push('Connection: keep-alive') if (reqData.auth) { const encodedAuth = Buffer.from(reqData.auth).toString('base64') headers.Authorization = `Basic ${encodedAuth}` @@ -62,12 +69,6 @@ function requestBuilder (defaults) { throw new Error(`${method} HTTP method is not supported`) } - const baseReq = [ - `${method} ${path} HTTP/1.1`, - `Host: ${host}`, - 'Connection: keep-alive' - ] - let bodyBuf if (typeof body === 'string') { diff --git a/test/httpRequestBuilder.test.js b/test/httpRequestBuilder.test.js index f030e596..4841ab2d 100644 --- a/test/httpRequestBuilder.test.js +++ b/test/httpRequestBuilder.test.js @@ -99,6 +99,23 @@ test('request builder should add a Content-Length header when the body buffer ex 'request is okay') }) +test('request builder should add only one HOST header', (t) => { + t.plan(1) + + const opts = server.address() + opts.method = 'POST' + opts.headers = { + Host: 'example.com' + } + + const build = RequestBuilder(opts) + + const result = build({ body: 'body' }) + t.same(result, + Buffer.from('POST / HTTP/1.1\r\nConnection: keep-alive\r\nHost: example.com\r\nContent-Length: 4\r\n\r\nbody'), + 'request is okay') +}) + test('request builder should add a Content-Length header with correct calculated value when the body buffer exists and idReplacement is enabled as a default override', (t) => { t.plan(1)