【问题标题】:Posting object array to sails causes 'TypeError: Cannot convert object to primitive value'将对象数组发布到sails 会导致“TypeError:无法将对象转换为原始值”
【发布时间】:2014-06-21 08:27:36
【问题描述】:

在我的 html 页面中,我将这篇文章发送到我的sails 服务器,但我无法访问控制器中的数据,因为 req.param() 函数没有返回任何有意义的答案。

这是网页代码

$.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"));
    });

这是控制器

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: {}
};

我尝试过使用 req.body 但它似乎不包含任何内容。 这就是我在输出中得到的

batch called
req.body=[object Object]
TypeError: Cannot convert object to primitive value
    at Array.toString (native)

【问题讨论】:

    标签: node.js express sails.js


    【解决方案1】:
    module.exports = {
     batch: function (req, res, next){
      console.log("batch called");
      console.log(req.body);
      console.log(req.param("batch"));
      res.send("ok");
    },
    
    _config: {}
    };
    

    如果你使用console.log("foo" + object),nodejs 会尝试将对象转换为字符串。只需console.log(object)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2011-08-02
      • 2019-10-16
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多