Permalink
Browse files

Fix JSON leading whitespaces handling in strict mode.

JSON allows leading whitespaces and is considered valid, according
to RFC 4627 http://www.ietf.org/rfc/rfc4627.txt .
  • Loading branch information...
1 parent 0943ca9 commit 0737981cc45d54353af52f1bb2e8c537488b3082 @cliffano cliffano committed Nov 9, 2012
Showing with 21 additions and 1 deletion.
  1. +2 −1 lib/middleware/json.js
  2. +19 −0 test/json.js
View
@@ -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(){

0 comments on commit 0737981

Please sign in to comment.