senchalabs/connect — Issue #434: bodyParser suggestion with json parsing
Author: beatgammit
Created: 2011-12-09 01:20:43+00:00
State: open

I am using connect 1.8.2, and when I POST a string without surrounding quotes, the client receives a huge error string.

This doesn't really seem like the intent, which was probably to send a JSON string, surrounded with double-quotes. IMHO, if a JSON.parse fails, it should set body to be the string value instead of spitting out an error.

Therefore, these requests should have an identical result:

`curl -X POST localhost:5000/ -d 'hello' -H 'Content-Type: application/json'`

`curl -X POST localhost:5000/ -d '"hello"' -H 'Content-Type: application/json'`

I can see how this would not be ideal for everyone (especially those who want to catch errors or depend on receiving a JSON object instead of a string), so bodyParser could either accept a param that tells it to ignore parse errors and just give the string, or there could be a simple regex to see if an input string is just a unquoted JSON string, something like this:

try {
req.body = JSON.parse(str);
fn();
} catch (err) {
if (!/^\s*[{\]]/.test(str)) {
req.body = str;
fn();
return;
}
fn(err);
}