Skip to content

Commit

Permalink
make user-agent and content-type overwritable with undefined (#216)
Browse files Browse the repository at this point in the history
* make user-agent and content-type undefinable

* Update test/test.js
  • Loading branch information
Uzlopak committed Aug 17, 2022
1 parent 9c4ca58 commit c3aa66f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,24 @@ function Request (options) {
const headers = options.headers || {}

for (const field in headers) {
const fieldLowerCase = field.toLowerCase()
if (
(
fieldLowerCase === 'user-agent' ||
fieldLowerCase === 'content-type'
) && headers[field] === undefined
) {
this.headers[fieldLowerCase] = undefined
continue
}
const value = headers[field]
assert(value !== undefined, 'invalid value "undefined" for header ' + field)
this.headers[field.toLowerCase()] = '' + value
this.headers[fieldLowerCase] = '' + value
}

this.headers['user-agent'] = this.headers['user-agent'] || 'lightMyRequest'
if (('user-agent' in this.headers) === false) {
this.headers['user-agent'] = 'lightMyRequest'
}
this.headers.host = this.headers.host || options.authority || hostHeaderFromURL(parsedURL)

if (options.cookies) {
Expand Down Expand Up @@ -143,7 +155,10 @@ function Request (options) {

if (payload && typeof payload !== 'string' && !payloadResume && !Buffer.isBuffer(payload)) {
payload = JSON.stringify(payload)
this.headers['content-type'] = this.headers['content-type'] || 'application/json'

if (('content-type' in this.headers) === false) {
this.headers['content-type'] = 'application/json'
}
}

// Set the content-length for the corresponding payload if none set
Expand Down
25 changes: 25 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1924,3 +1924,28 @@ test('should work with pipeline', (t) => {
t.equal(res.rawPayload.toString(), 'example.com:8080|/hello')
})
})

test('should leave the headers user-agent and content-type undefined when the headers are explicitly set to undefined in the inject', (t) => {
t.plan(5)
const dispatch = function (req, res) {
t.ok(Array.isArray(req.rawHeaders))
t.equal(req.headers['user-agent'], undefined)
t.equal(req.headers['content-type'], undefined)
t.equal(req.headers['x-foo'], 'bar')
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Ok')
}

inject(dispatch, {
url: 'http://example.com:8080/hello',
method: 'POST',
headers: {
'x-foo': 'bar',
'user-agent': undefined,
'content-type': undefined
},
body: {}
}, (err, res) => {
t.error(err)
})
})

0 comments on commit c3aa66f

Please sign in to comment.