本文介绍了将对象数组发布到帆会导致"TypeError:无法将对象转换为原始值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的html页面中,我将此帖子发送到我的Sails服务器,但是由于req.param()函数未返回任何有意义的答案,因此无法访问控制器中的数据.

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.

这是网页代码

$.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,但似乎不包含任何内容.这就是我在输出中得到的

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)

推荐答案

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)

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

这篇关于将对象数组发布到帆会导致"TypeError:无法将对象转换为原始值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 03:41