Skip to content

Commit

Permalink
Merge pull request #1525 from froatsnook/1522-undefined-headers
Browse files Browse the repository at this point in the history
Delete request headers with undefined value.
  • Loading branch information
simov committed Apr 5, 2015
2 parents f157a25 + 3f914bb commit 204dbe0
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
8 changes: 8 additions & 0 deletions request.js
Expand Up @@ -323,6 +323,14 @@ Request.prototype.init = function (options) {
}
self.headers = self.headers ? copy(self.headers) : {}

// Delete headers with value undefined since they break
// ClientRequest.OutgoingMessage.setHeader in node 0.12
for (var headerName in self.headers) {
if (typeof self.headers[headerName] === 'undefined') {
delete self.headers[headerName]
}
}

caseless.httpify(self, self.headers)

if (!self.method) {
Expand Down
18 changes: 18 additions & 0 deletions tests/test-defaults.js
Expand Up @@ -23,6 +23,14 @@ tape('setup', function(t) {
resp.end()
})

s.on('/foo-no-test', function(req, resp) {
assert.equal(req.headers.foo, 'bar')
assert.equal('test' in req.headers, false)
assert.equal(req.method, 'GET')
resp.writeHead(200, {'Content-Type': 'text/plain'})
resp.end('TESTING!')
})

s.on('/post', function (req, resp) {
assert.equal(req.headers.foo, 'bar')
assert.equal(req.headers['content-type'], null)
Expand Down Expand Up @@ -136,6 +144,16 @@ tape('merge headers', function(t) {
})
})

tape('default undefined header', function(t) {
request.defaults({
headers: { foo: 'bar', test: undefined }
})(s.url + '/foo-no-test', function(e, r, b) {
t.equal(e, null)
t.equal(b, 'TESTING!')
t.end()
})
})

tape('post(string, object, function)', function(t) {
request.defaults({
headers: { foo: 'bar' }
Expand Down
24 changes: 24 additions & 0 deletions tests/test-headers.js
Expand Up @@ -18,6 +18,14 @@ s.on('/redirect/to', function(req, res) {
res.end('ok')
})

s.on('/headers.json', function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json'
})

res.end(JSON.stringify(req.headers))
})

tape('setup', function(t) {
s.listen(s.port, function() {
t.end()
Expand Down Expand Up @@ -138,6 +146,22 @@ tape('upper-case Host header and redirect', function(t) {
})
})

tape('undefined headers', function(t) {
request({
url: s.url + '/headers.json',
headers: {
'X-TEST-1': 'test1',
'X-TEST-2': undefined
},
json: true
}, function(err, res, body) {
t.equal(err, null)
t.equal(body['x-test-1'], 'test1')
t.equal(typeof body['x-test-2'], 'undefined')
t.end()
})
})

tape('cleanup', function(t) {
s.close(function() {
t.end()
Expand Down

0 comments on commit 204dbe0

Please sign in to comment.