Skip to content

Commit

Permalink
Merge pull request #1656 from simov/fix-form-method
Browse files Browse the repository at this point in the history
Fix form method
  • Loading branch information
simov committed Jun 26, 2015
2 parents f57ad7c + 986723e commit ef8c525
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 19 deletions.
31 changes: 14 additions & 17 deletions request.js
Expand Up @@ -430,28 +430,24 @@ Request.prototype.init = function (options) {
self.elapsedTime = self.elapsedTime || 0
}

if (self.body) {
var length = 0
if (!Buffer.isBuffer(self.body)) {
if (Array.isArray(self.body)) {
for (var i = 0; i < self.body.length; i++) {
length += self.body[i].length
}
} else {
self.body = new Buffer(self.body)
length = self.body.length
}
} else {
length = self.body.length
function setContentLength () {
if (!Buffer.isBuffer(self.body) && !Array.isArray(self.body)) {
self.body = new Buffer(self.body)
}
if (length) {
if (!self.hasHeader('content-length')) {
if (!self.hasHeader('content-length')) {
var length = (Array.isArray(self.body))
? self.body.reduce(function (a, b) {return a + b.length}, 0)
: self.body.length
if (length) {
self.setHeader('content-length', length)
} else {
self.emit('error', new Error('Argument error, options.body.'))
}
} else {
self.emit('error', new Error('Argument error, options.body.'))
}
}
if (self.body) {
setContentLength()
}

if (options.oauth) {
self.oauth(options.oauth)
Expand Down Expand Up @@ -541,6 +537,7 @@ Request.prototype.init = function (options) {
self._multipart.body.pipe(self)
}
if (self.body) {
setContentLength()
if (Array.isArray(self.body)) {
self.body.forEach(function (part) {
self.write(part)
Expand Down
12 changes: 10 additions & 2 deletions tests/test-form-urlencoded.js
Expand Up @@ -9,11 +9,12 @@ function runTest (t, options, index) {

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

if (index === 0) {
if (index === 0 || index === 3) {
t.equal(req.headers['content-type'], 'application/x-www-form-urlencoded')
} else {
t.equal(req.headers['content-type'], 'application/x-www-form-urlencoded; charset=UTF-8')
}
t.equal(req.headers['content-length'], '21')
t.equal(req.headers.accept, 'application/json')

var data = ''
Expand All @@ -33,14 +34,17 @@ function runTest (t, options, index) {

server.listen(6767, function() {

request.post('http://localhost:6767', options, function(err, res, body) {
var r = request.post('http://localhost:6767', options, function(err, res, body) {
t.equal(err, null)
t.equal(res.statusCode, 200)
t.equal(body, 'done')
server.close(function() {
t.end()
})
})
if (!options.form && !options.body) {
r.form({some: 'url', encoded: 'data'})
}
})
}

Expand All @@ -58,6 +62,10 @@ var cases = [
headers: {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: 'some=url&encoded=data',
json: true
},
{
// body set via .form() method
json: true
}
]

Expand Down

0 comments on commit ef8c525

Please sign in to comment.