An error message has been triggered due to an invalid JSON format, relating to the

I have been immersing myself in learning the MEAN stack and am currently engrossed in building a simple Todo application.

However, I keep encountering this JSON error:

POST /api/todos 400 20.659 ms - 612
Error: invalid json
at parse (/Users/Angular_To_Do/node_modules/body-parser/lib/types/json.js:60:15)
at /Users/Angular_To_Do/node_modules/body-parser/lib/read.js:96:18
at IncomingMessage.onEnd (/Users/Angular_To_Do/node_modules/body-parser/node_modules/raw-body/index.js:136:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)

As a beginner, I have thoroughly checked my code for errors, but I cannot seem to pinpoint what is causing this issue. I have set up app.use(bodyParser.json()) to send a JSON object, yet it still does not work. Please enlighten me on why this might be happening…

//Server.js

app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride('X-HTTP-Method-Override'));


var Todo = mongoose.model('Todo', {
text : String
});

app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
    if(err){
        res.send(err)
    }

    res.json(todos)
      });
});

app.post('/api/todos', function(req, res){
    Todo.create({
    text: req.body.text,
    done: false
}, function(err, todo){
    if(err){
        res.send(err);
    }

    Todo.find(function(err,todos){
        if(err){
            res.send(err)
        }
        res.json(todos);
       });
    });
});

Here is the Controller file:

var myTodo = angular.module('myTodo',[ ])

myTodo.controller('taskController',function($scope, $http){

  $http.get('/api/todos')
     .success(function(data){
        $scope.todos = data;
        console.log(data);
     })
     .error(function(data){
        console.log('Error: ' + data);
    });

  $scope.addListItem = function(){
     $http.post('/api/todos', $scope.formData)
       .success(function(data){
        $scope.formData = "";
        $scope.todos = data;
        console.log(data);
     })
     .error(function(data){
        console.log('Error: ' + data);

     });
  };

Please see the HTML snippet here:

 <div ng-controller = "taskController">
  <form>
    <input type="text" class="" placeholder="" ng-model="formData">
    <button style = "margin-top:50px"
     type = "submit"
     ng-click = "addListItem()">
     ADD SOME TASKS
    </button>
  </form>
</div>

I am using Express 4.7 and Angular 1.3.15. Despite my efforts, I am unable to progress beyond this error. Your guidance would be greatly appreciated. Thank you.

Answer №1

For handling POST and GET requests for an object, it is recommended to execute them asynchronously within the server controller. It is more efficient to send the JSON object on the frontend after a successful post.

You can achieve this by:

app.post('/api/todos', function(req, res) {
  var newTodo = new Todo();

  newTodo.text = req.body.text 

  newTodo.save(function(err, todo) {
    if(err) {
      res.send('error ' + err);
    }
    res.json(todo);
  });

On the frontend side:

$scope.todos.splice(0, 0, data);

It's crucial to define a variable while making a POST request and submit that variable instead of passing all data attached to $scope.formData as the second variable.

$scope.addListItem = function(){
var formData = { text: $scope.formData.text };

$http.post(url, formData)
   .success(...)

Your solution worked because you were passing all data attached to $scope.formData.

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

The then() function in Node.js is triggered before the promise is fully resolved

I'm struggling to get my Promise function working as intended. Here's what I need to accomplish: I am receiving file names from stdout, splitting them into lines, and then copying them. Once the copy operation is complete, I want to initiate oth ...

Limit the allowed inputs for the function to match the specified regex pattern

I have a function that takes an array as input, which can contain any number of values. I also have a string that specifies the desired final format. For instance: function doFormat(args) { const format = 'Foo \\d{1,2}x\\d{2} B ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...

Is there a maximum number of divisions that can be nested within a canvas element?

My webGL(threejs) rendering in canvas inside a div is functioning as expected with the original structure below... <body> <div id='header'></div> <div id="webGLDiv"> <script></script> </div&g ...

Retrieving information from the shader

I am currently delving into the realm of leveraging GPU capabilities for threejs and webgl applications. My approach involves closely analyzing code to uncover patterns, methodologies, and seeking explanations on certain code segments. During my quest for ...

Mouse over effect to highlight the crosshair on a table

My code currently enables a crosshair function, but I am looking for a way to limit the highlight effect only within the cursor (hover) area. Instead of highlighting in a "cross" shape, I would like it to show a backward "L" shape. This means that the hig ...

I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following. I have successfully executed the loop and managed to display it on my frontend desi ...

`Testing the functionality of the window.onload JavaScript function with the Jasmine testing framework`

Currently, I am experimenting with the window.onload function using the jasmine framework. Below is my JavaScript code snippet - window.onload = windowonloadFunction(); function windowonloadFunction(){ if('WebSocket' in window){ docume ...

Comparing JavaScript dependency management tools: npm, bower, and volo

When considering npm, bower, and volo, how do they stack up against each other? All three serve the purpose of installing JavaScript dependencies for a UI project. It's known that npm is more tailored towards node applications. So, in what scenarios ...

How can you trigger multiple jQuery Ajax calls simultaneously from various events?

Currently, I am facing a challenge with the development of a webpage that relies on multiple Ajax calls using jQuery to populate its contents. The issue lies in the fact that each call is waiting for the previous one to finish, causing slow loading times. ...

Error: JSON parsing error encountered at position x due to unexpected token

While I understand this question has been asked multiple times before, the situation here is unique. I am utilizing getJSON to retrieve data from a Database. The returned result is a valid JSON (validated by various JSON validators), but I am encountering ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

What is the correct location for storing the mapping files in Elasticsearch?

I'm finding the ES documentation confusing. According to this page, it says that indexes should go in the mapping directory along with indexname subdirectories: Mappings can be defined within files named [mapping_name].json and placed in either the ...

Ways to remove a specific row in Node.js using express

How do I remove data from a list in Node.js, using express and ejs view? I have attempted it but without success. My project involves the use of mongodb. This is what I have implemented so far, but with no luck. router.post('/delete', function( ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

When the ASPxComboBox component is situated within two ASPxPageControl tab pages, I am unable to access it

I am encountering an issue with accessing the ASPxComboBox component when it is within an ASPxPageControl that has multiple tab pages. To handle this, I have added a function to the ClientSideEvents using string.Format: function(s, e) {{ if (window[ ...

Unveiling the mystery: Converting the MD5 hash from Google Cloud Storage into a decipherable string using hash generators in Node JS

When dealing with Google cloud storage, one may encounter MD5 hashes of objects encoded in base64. For instance, H0m5T/tigkNJLqL6+z9A7Q== is an example of such a hash. Attempting to convert it using btoa() leads to the unexpected result of I9O{bCI."z{?@m, ...

Error: A property called 'node' is undefined and cannot be read

Currently attempting to complete the NPM installation process. I initiated with the following command: brew install node followed by curl -O https://www.npmjs.org/install.sh and then ~ % sh install.sh The resultant output is as follows: tar=/usr/bi ...

Where do I find the resultant value following the completion of a video production through editly?

Hey there, I have a quick question... I was following the instructions in the README for editly, and I successfully created videos by calling editly like this: // creating video editly(editSpec) .catch(console.error); The only issue is that I am using Ex ...