Fix JSON leading whitespaces handling in strict mode. #690

Merged
merged 1 commit into from Nov 9, 2012
@@ -65,7 +65,8 @@ exports = module.exports = function(options){
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function(){
- if (strict && '{' != buf[0] && '[' != buf[0]) return next(utils.error(400, 'invalid json'));
+ var first = buf.trim()[0];
+ if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));
try {
req.body = JSON.parse(buf, options.reviver);
next();
View
@@ -122,6 +122,25 @@ describe('connect.json()', function(){
done();
});
})
+
+ it('should allow leading whitespaces in JSON', function(done){
+ var app = connect();
+ app.use(connect.json({ strict: true }));
+
+ app.use(function(req, res){
+ res.end(JSON.stringify(req.body));
+ });
+
+ app.request()
+ .post('/')
+ .set('Content-Type', 'application/json')
+ .write(' { "user": "tobi" }')
+ .end(function(res){
+ res.should.have.status(200);
+ res.body.should.include('{"user":"tobi"}');
+ done();
+ });
+ })
})
describe('by default', function(){