Node.js encountered an abrupt conclusion in the JSON input that was not anticipated

Upon receiving Json data as post data in my node.js server, I encountered an issue with parsing the string.

Here is a snippet of 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);
   }

An error occurs when attempting to parse the json 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 confirmed the JSON data's syntax using JSONLint and it was error-free. I'm unsure about what may be causing this issue or how to resolve it.

Answer №1

Information may trigger several events, requiring you to gather all the data values and combine them once the end event is triggered:

let pieces = [];

req.on('details', function(data) {
  pieces.push(data);
}).on('finish', function() {
  let details   = Buffer.concat(pieces);
  let structure = JSON.parse(details);
  ...
});

Consider using body-parser as an alternative solution.

Answer №2

Modification needed on this line

currentSchema = JSON.parse(data);

Change it to

currentSchema = JSON.parse(JSON.stringify(data));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the purpose of passing data into the 'success' function of an AJAX request?

Recently, I embarked on a journey to learn jQuery and AJAX, but I found myself tangled in confusion when it came to AJAX requests. To gain practice, I decided to create a simple TodoApp using Node, jQuery, and Bootstrap. While I managed to grasp GET and P ...

The Issue of Express Session Unable to Save or Locate the Session

My current issue involves using express-session to utilize sessions, but it seems unable to locate or store the session properly. Upon making repeated requests through Postman or a basic Svelte app, I expect the response to increment with each call. Howev ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

When attempting to pass a value using the JSON Extractor feature in JMeter, I found that only the default value was successfully passed

My issue with passing the correct value from the JSON Extractor to the next call in my JMeter script may stem from an expression problem. https://i.stack.imgur.com/fFuw7.jpg https://i.stack.imgur.com/JlG6q.jpg This is how the Response JSON appears: {"u ...

Babel asyncToGenerator causing NextJS getInitialProps to be invoked twice

It came to my attention that my getInitialProps function was being called multiple times, sometimes even three times. One call was from the user's request, while the others were coming from babel asyncToGenerator as shown below: localhost/[page]/babe ...

A request sent from a react.js frontend is being processed as a GET request on a node

My POST request seems to be getting converted to a GET request somewhere in my REACT client code. Here is the react code snippet: function SavePatient(event) { event.preventDefault(); console.log("Saving Patient Data"); console.log(patient ...

Having trouble with sending POST data to server while trying to save to a JSON file using ajax and php

I attempted to follow the instructions from various stackoverflow posts, but it seems that my server is not acknowledging any incoming requests. I am certain that the client is sending the request because it can be seen in the Firefox debugger tool. Below ...

The node module fails to ignore its own node_modules directory, causing issues during deployment on Heroku

I'm currently facing an issue with the aws-sdk module. The problem lies in its .gitignore file which is ignoring its own node_modules directories, causing complications with my Heroku deployment. Has anyone come across a similar situation and found a ...

Issue with joining tables in query on Cordova Mobile app

I have 2 queries that will return results which I plan to use in JSON format. The first query is $query = "SELECT * FROM info_location WHERE location_id=".$id.""; and the second query $query = "SELECT t1.location_id,t1.street,t1 ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

Exploring Express' GET Routes: Mastering the Art of Keeping Your Code D

I have the following code to retrieve process paths: router.get( "/todoHome", ( req, res ) => { res.render( "todoHome", { title: 'My Todo List!!' } ); } ); router.get( "/articles", ( req, res ) => { res.render( "articles", ...

Node.js package installation was unsuccessful

Recently, I've encountered an issue while trying to install node.js npm packages. Whenever I attempt to install them, the installation process starts but then unfortunately freezes. Strangely, when I try to install angular packages, there are no issue ...

Should we retain the express variable for a specific purpose?

Being a developer who is still learning the ropes, I fail to understand the necessity of creating or retaining the express variable in an express/Node app. Instead of following this conventional approach: const express = require('express'); con ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...

Render HTML with Node JS and Express, then initiate file download using the same GET request

Looking for a solution to send a landing page via email link and initiate a file download using the same GET request. I want to be able to render a Handlebar template with Express Static and also trigger a file download in the same request flow. Since req ...

Exploring the JSON Array in Angular5 with the power of ngFor

Currently, I am working on a project using Angular5 and encountering an issue with the *ngFor directive. The model class I have defined looks like this: export class FetchApi { value: Array<String>; api_status: string; api_version: string; d ...

Hot reloading in React

Currently working on a React project that was initiated with create-react-app. However, I am experiencing inconsistencies with the hot reload feature. Sometimes it works for a brief period of time, then stops functioning, requiring me to restart the serv ...

Use React-table to store the value of an accessor in the state while also utilizing a

I am currently working on implementing a checkbox table using react-table. The primary objective is to have checkboxes in the first column, and upon selection of a checkbox, I intend to store the ID defined in the accessor in the state. Despite going thro ...

Unable to retrieve JSON data from a PHP file hosted on the server

I have a server-side database with a table called "customers" and a column named "names". My goal is to send a request to the server asking for the first two records in the "customers" table. However, when I execute the program, the browser does not displa ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...