Skip to content

Loading…

Specific error message for content-type of JSON but empty body. #698

Merged
merged 2 commits into from

2 participants

@evdb

As suggested in comments to #680

I spent some time trying to debug this. A more verbose error message would have guided me to the problem straight away.

Tests updated too :)

@tj tj commented on an outdated diff
lib/middleware/json.js
@@ -66,6 +66,13 @@ exports = module.exports = function(options){
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
var first = buf.trim()[0];
+
+ if ( buf.length == 0 ) {
@tj Sencha Labs member
tj added a note

if (0 == buf.length) no jquery parens :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@tj tj commented on an outdated diff
lib/middleware/json.js
@@ -66,6 +66,13 @@ exports = module.exports = function(options){
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
var first = buf.trim()[0];
+
+ if ( buf.length == 0 ) {
+ // content-type says json, but no body. Provide specific error message to help
+ // debug. This is often due to a library not creating valid requests.
+ return next( utils.error( 400, "invalid json - request content-type is 'application/json' but request body empty") );
@tj Sencha Labs member
tj added a note

same here, also I'd ditch the comment personally since the string describes it already. Maybe change the response to "invalid json, empty body"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@evdb

your wish, my command, etc :)

@tj tj merged commit be4a240 into senchalabs:master

1 check passed

Details default The Travis build passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 29, 2012
  1. @evdb
Commits on Dec 6, 2012
  1. @evdb
Showing with 10 additions and 1 deletion.
  1. +5 −0 lib/middleware/json.js
  2. +5 −1 test/json.js
View
5 lib/middleware/json.js
@@ -66,6 +66,11 @@ exports = module.exports = function(options){
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
var first = buf.trim()[0];
+
+ if (0 == buf.length) {
+ return next(utils.error(400, "invalid json, empty body"));
+ }
+
if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));
try {
req.body = JSON.parse(buf, options.reviver);
View
6 test/json.js
@@ -67,7 +67,11 @@ describe('connect.json()', function(){
app.request()
.post('/')
.set('Content-Type', 'application/json')
- .expect(400, done);
+ .end(function(res) {
+ res.should.have.status(400);
+ res.body.should.include("invalid json, empty body");
+ done();
+ })
})
it('should support all http methods', function(done){
Something went wrong with that request. Please try again.