Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected end of json input in Node.js

I have Json data which I receive it as post data in my node.js server.

But the problem is, its not able to parse the string I sent.Here is my node.js server code.

res.header("Access-Control-Allow-Origin", "*");
  req.on('data',function(data)
  {
    var done=false;
    console.log(data);
    var schema;

    schema=JSON.parse(data);
   }

Here I get the error when I parse the json data(data).

undefined:776



SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/Users/as6/Documents/test/server.js:206:17)
    at emitOne (events.js:115:13)
    at IncomingMessage.emit (events.js:210:7)
    at IncomingMessage.Readable.read (_stream_readable.js:462:10)
    at flow (_stream_readable.js:833:34)
    at resume_ (_stream_readable.js:815:3)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)

I verified JSON data using JSONLint for syntax errors.But it was absolutely fine. I dont know what's wrong and how to correct it.

like image 426
Akash Sateesh Avatar asked Jul 11 '17 08:07

Akash Sateesh


People also ask

How do I fix unexpected end of JSON input in node JS?

You can solve the "Unexpected end of JSON input" error in the following 3 ways: wrap your parsing logic in a try/catch block. make sure to return a valid JSON response from your server. remove the parsing logic from your code if you are expecting an empty server response.

What is unexpected end of JSON input?

A common error encountered by JavaScript programmers is the Uncaught SyntaxError: Unexpected end of JSON input. This is usually observed when the coder is trying to convert a string into a JSON Object.

What does unexpected JSON mean?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.


2 Answers

data events can be fired multiple times, so you have to collect all the data values and concatenate them together when the end event has fires:

let chunks = [];

req.on('data', function(data) {
  chunks.push(data);
}).on('end', function() {
  let data   = Buffer.concat(chunks);
  let schema = JSON.parse(data);
  ...
});

However, perhaps you should consider using body-parser.

like image 103
robertklep Avatar answered Oct 23 '22 11:10

robertklep


Do change the line

schema = JSON.parse(data);

into

schema = JSON.parse(JSON.stringify(data));
like image 34
Owais Ibrahim Avatar answered Oct 23 '22 12:10

Owais Ibrahim