Skip to content

Commit

Permalink
Merge pull request #1314 from simov/fix-urlencoded-header-detection
Browse files Browse the repository at this point in the history
Detect urlencoded form data header via regex
  • Loading branch information
nylen committed Dec 14, 2014
2 parents d3fd7e3 + f5a07a6 commit 0ffa30b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
2 changes: 1 addition & 1 deletion request.js
Expand Up @@ -1482,7 +1482,7 @@ Request.prototype.json = function (val) {

self._json = true
if (typeof val === 'boolean') {
if (self.body !== undefined && self.getHeader('content-type') !== 'application/x-www-form-urlencoded') {
if (self.body !== undefined && !/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
self.body = safeStringify(self.body)
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
Expand Down
30 changes: 22 additions & 8 deletions tests/test-form-urlencoded.js
Expand Up @@ -5,11 +5,11 @@ var http = require('http')
, tape = require('tape')


tape('application/x-www-form-urlencoded', function(t) {
function runTest (t, options) {

var server = http.createServer(function(req, res) {

t.equal(req.headers['content-type'], 'application/x-www-form-urlencoded')
t.ok(req.headers['content-type'].match(/application\/x-www-form-urlencoded/))
t.equal(req.headers.accept, 'application/json')

var data = ''
Expand All @@ -24,21 +24,35 @@ tape('application/x-www-form-urlencoded', function(t) {

res.writeHead(200)
res.end('done')

t.end()
})
})

server.listen(8080, function() {

request.post('http://localhost:8080', {
form: {some: 'url', encoded: 'data'},
json: true
}, function(err, res, body) {
request.post('http://localhost:8080', options, function(err, res, body) {
t.equal(err, null)
t.equal(res.statusCode, 200)
t.equal(body, 'done')
server.close()
t.end()
})
})
}

var cases = [
{
form: {some: 'url', encoded: 'data'},
json: true
},
{
headers: {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: 'some=url&encoded=data',
json: true
}
]

cases.forEach(function (options, index) {
tape('application/x-www-form-urlencoded ' + index, function(t) {
runTest(t, options)
})
})

0 comments on commit 0ffa30b

Please sign in to comment.