cojs / co-body

Parse request bodies with co
MIT License
325 stars 42 forks source link

Fix content-length zero should not parse json #15

Closed nunofgs closed 9 years ago

nunofgs commented 9 years ago

This PR fixes an issue where a POST request with a header of Content-Length: 0 and no body will return an HTTP 400 error.

According to RFC2730 Section 3.3.2:

"For example, a Content-Length header field is normally sent in a POST request even when the value is 0 (indicating an empty payload body)."

I experienced this issue using the Guzzle PHP framework which sends a "Content-Length: 0" header even when _POST_ing without a body but it has also been reported with jQuery clients.

I have also found that cURL makes the same assumption. For example:

curl http://localhost:3000/ -H 'accept: application/json' -d ''

This will cause cURL to add a Content-Length: 0 header and ultimately trigger an HTTP 400 response.

The issue has also been discussed on the type-is project where @jonathanong mentioned that parsers will need to check if the body is empty. (which is what this PR implements)

Additionally, express' body-parser package has also addressed this issue by always returning an empty object.

I personally believe that returning null is more appropriate since it makes no assumptions on the client, i.e.: why not return an empty array? or an empty string with double-quotes? all are equally valid JSON.

fixe commented 9 years ago

Thoughts @tj?

fengmk2 commented 9 years ago

Landed 90b88a0262f0c19de3f334cd0ba192dd90553cbe

fengmk2 commented 9 years ago

co-body@1.1.0 publish now!