Skip to content

Commit

Permalink
Set default application/json content-type when using json option
Browse files Browse the repository at this point in the history
Will set the header when using `json: true` without a body.
  • Loading branch information
jzaefferer committed Sep 15, 2015
1 parent cd928c4 commit 5225289
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
9 changes: 3 additions & 6 deletions request.js
Expand Up @@ -1198,22 +1198,19 @@ Request.prototype.json = function (val) {
}

self._json = true
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
if (typeof val === 'boolean') {
if (self.body !== undefined) {
if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
self.body = safeStringify(self.body)
} else {
self.body = self._qs.rfc3986(self.body)
}
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
}
} else {
self.body = safeStringify(val)
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
}

if (typeof self.jsonReviver === 'function') {
Expand Down
5 changes: 3 additions & 2 deletions tests/test-defaults.js
Expand Up @@ -73,6 +73,7 @@ tape('deep extend', function(t) {
}, function (e, r, b) {
delete b.headers.host
delete b.headers.accept
delete b.headers['content-type']
delete b.headers.connection
t.deepEqual(b.headers, { a: '1', b: '3', c: '4' })
t.deepEqual(b.qs, { a: '1', b: '3', c: '4' })
Expand All @@ -97,7 +98,7 @@ tape('post(string, object, function)', function(t) {
}).post(s.url + '/', { json: true }, function (e, r, b) {
t.equal(b.method, 'POST')
t.equal(b.headers.foo, 'bar')
t.equal(b.headers['content-type'], undefined)
t.equal(b.headers['content-type'], 'application/json')
t.end()
})
})
Expand All @@ -108,7 +109,7 @@ tape('patch(string, object, function)', function(t) {
}).patch(s.url + '/', { json: true }, function (e, r, b) {
t.equal(b.method, 'PATCH')
t.equal(b.headers.foo, 'bar')
t.equal(b.headers['content-type'], undefined)
t.equal(b.headers['content-type'], 'application/json')
t.end()
})
})
Expand Down

1 comment on commit 5225289

@thecadams
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi guys,
Thanks for this library, it's really useful.
Looks like this commit is breaking our services because Content-Type header shouldn't be set on GET requests.
Issue is here: #1786

Cheers
Chris.

Please sign in to comment.