Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js and json runtime error

Tags:

json

node.js

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"
}
like image 397
The Learner Avatar asked Nov 03 '12 20:11

The Learner


People also ask

Is node JS and JSON same?

With node. js as backend, the developer can maintain a single codebase for an entire application in javaScript. JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging data.

What is Enoent error in Nodejs?

The code ENOENT means that npm fails to open a file or directory that's required for executing the command. The npm start command is used to run the start script in the package. json file.25-Jun-2022.

What is a Nodejs runtime?

The Node. js runtime is the software stack responsible for installing your web service's code and its dependencies and running your service. The Node.js runtime for App Engine in the standard environment is declared in the app.yaml file: Node.js 16.


1 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);
});
like image 69
Pastor Bones Avatar answered Sep 26 '22 19:09

Pastor Bones