Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting object array to sails causes 'TypeError: Cannot convert object to primitive value'

In my html page i am sending this post to my sails server but I cannot get to the data in my controller as the req.param() function does not return any meaningful answer.

Here is the web page code

$.post("http://myserver.local/calendar/batch",
            {"batch":[
                {
                    "start_date" : "2014-06-27T09:00:00Z",
                    "title" : "abc",
                    "attendees" : [
                        "Fred Bloggs",
                        "Jimmy Jones",
                        "The Queen"
                    ],
                    "event_id" : "123",
                    "location" : "Horsham, United Kingdom",
                    "end_date" : "2014-06-27T10:30:00Z"
                },
                {
                    "start_date" : "2014-06-27T09:00:00Z",
                    "title" : "another",
                    "attendees" : [
                        "Fred Bloggs",
                        "Jimmy Jones",
                        "The Queen"
                    ],
                    "event_id" : "def",
                    "location" : "Horsham, United Kingdom",
                    "end_date" : "2014-06-27T10:30:00Z"
                }
            ]},
    function (data) {
        console.log("success");
    }
    ).fail(function(res){
        console.log("Error: " + res.getResponseHeader("error"));
    });

Here is the controller

module.exports = {
  batch: function (req, res, next){
    console.log("batch called");
    console.log("req.body" + req.body);
    console.log("req.param()" + req.param());
    res.send("ok");
  },

  _config: {}
};

I have tried using req.body but that does not seem to contain any content. This is what i get in the output

batch called
req.body=[object Object]
TypeError: Cannot convert object to primitive value
    at Array.toString (native)
like image 345
simondelliott Avatar asked Jun 21 '14 08:06

simondelliott


1 Answers

module.exports = {
 batch: function (req, res, next){
  console.log("batch called");
  console.log(req.body);
  console.log(req.param("batch"));
  res.send("ok");
},

_config: {}
};

If you use console.log("foo" + object) nodejs will try to convert the obeject into a string. Simply do console.log(object)

like image 195
mdunisch Avatar answered Nov 15 '22 05:11

mdunisch