Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make user-agent and content-type overwritable with undefined #216

Merged
merged 2 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
})
})