node.js and json runtime error

I am using node.js and trying to parse the JSON body of a request. I am getting the following error:

undefined:0

^
SyntaxError: Unexpected end of input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (C:\node\xxxx.js:36:14)
    at IncomingMessage.emit (events.js:64:17)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:130:23)
    at Socket.ondata (http.js:1506:22)
    at TCP.onread (net.js:374:27)

I am doing:

     request.on('data', function(chunk)
    {
    data+=chunk;
    });
     // and in the end I am doing
     obj = JSON.parse(data);  // it's complaining at this point.

input is:

{
    "result": "success",
    "source": "chat"
}

Answers


You're trying to parse the data before it is completely recieved...put your JSON.parse inside the .end method of request

var data = '';
request.on('data', function(chunk){
  data += chunk;
});
request.on('end', function(){
  var obj = JSON.parse(data);
});

With your edit: where in your code are you doing JSON.parse? Remember that request.on is async; you can't call JSON.parse until the data is done (request.on('end'))... if you're just calling it next, then you're likely calling it before the data has arrived.

E.g.

request.on('data', function(chunk)
    {
    data+=chunk;
    });

request.on('end', function() {
     obj = JSON.parse(data);
});

would work, but

request.on('data', function(chunk)
    {
    data+=chunk;
    });

obj = JSON.parse(data);

will not, because the JSON.parse will likely get called before any 'data' callbacks fire.


"Unexpected end of input" is the error message you'll get from trying to parse an empty string or incomplete JSON string:

// examples
JSON.parse('')
JSON.parse('{')

So it sounds like your data source is unreliable. The proper way to handle this is to return a 400-range response to the client if/when the JSON.parse() step fails.


function connectionHandler(request, response) {
    var data = '';

    request.on('data', function(buffer) {
        data += buffer;
    });

    request.on('end', function() {
        response.writeHead(200, {
            'Content-Type': 'application/json'
        });

        try {
            data = JSON.parse(data.toString());
        } catch (e) {
            response.end();
            return;
        }

        if (!data) {
            return;
        }

        // process "data" here
    })
}

Need Your Help

Mac OS App wont run

compiler-construction loading

Hello i'm trying to build a simple web browser and when i try to run the program inside the xcode builder it says build suceded and then throughs a error and stop loading

What's the correct way to rename a heroku app?

heroku heroku-toolbelt

Doesn't seem to be a way to do it from the command line, and when I do this from the site, I run into this issue when I try to git push heroku master: