【问题标题】:Why is my JSON not transferred correctly from clientside to serverside为什么我的 JSON 没有正确地从客户端传输到服务器端
【发布时间】:2015-03-26 01:40:22
【问题描述】:

我有以下 JSON:

{
  "fields":[
    {"name":"thom","techname":"rgom","description":"dfgkjd","type":"text"},
    {"name":"thom","techname":"rgom2","description":"dfgkjd","type":"text"}
   ]
}

当我使用此代码将其发布到 NodeJS 服务器时:

    $.ajax({ 
      data : data, 
      type: 'POST',
      dataType: 'json',
      timeout: 10000,         
      url : '/schema/create', 
      success : function(response) {
        console.log(response)
      },
      complete : function() {
      },
      error: function(x, t, m) {
        if(t==="timeout") {
          alert("Timeout");
        } else {
          alert("Der opstod følgende fejl:" + t + x + m + ". Kontakt COWI");
        }
      }

    });

然后插入:

db.collection('schemas').insert(fields, {upsert:true}, function(err, result) {
  if(!err){
    console.log("written");
    console.log(result);

  }
});

在 MongoDB 中我有:

"_id" : ObjectId("5512ed12ecacf6e01da7aaa4"),
"fields[0][name]" : "thom",
"fields[0][techname]" : "rgom",
"fields[0][description]" : "dfgkjd",
"fields[0][type]" : "text",
"fields[1][name]" : "thom",
"fields[1][techname]" : "rgom2",
"fields[1][description]" : "dfgkjd",
"fields[1][type]" : "text"

我期待:

{
  "_id":ObjectId("5512ed12ecacf6e01da7aaa4"),
  "fields":
  [
    {
      "name":"thom", 
      "techname" : "rgom",
      "description" : "dfgkjd",
      "type" : "text"
    },
    {
      "name":"thom", 
      "techname" : "rgom2",
      "description" : "dfgkjd",
      "type" : "text"
    }
  ]
}

编辑: 插入前记录:

[ { 'fields[0][name]': 'thom',
    'fields[0][techname]': 'rgom',
    'fields[0][description]': 'dfgkjd',
    'fields[0][type]': 'text',
    'fields[1][name]': 'thom',
    'fields[1][techname]': 'rgom2',
    'fields[1][description]': 'dfgkjd',
    'fields[1][type]': 'text',
    _id: 5512ed12ecacf6e01da7aaa4 } ]

编辑 2 插入前记录控制台(使用 JSON.stringify()):

{
        "_id" : ObjectId("5512f0d4606391f41ddd16d1"),
        "{"fields":[{"name":"sdkljg","techname":"fgklj","description":"dfgklj","
type":"text"}]}" : ""
}

【问题讨论】:

  • 两者看起来相同,只是记录方式不同。你从哪里得到“fields[n][field_name]”类型的输出
  • db.schemas.find().pretty() 在 mongo-console - 我认为它们看起来不等价 - 因为引用了“fields [1] [description]”,因此是一个名称.
  • console.log(fields) 在插入语句之前。
  • 另外,在客户端,data 是什么?一个对象,或者一个字符串。
  • 在客户端数据是一个对象

标签: json node.js mongodb


【解决方案1】:

您在数据库插入之前记录fields 时获得的格式表明您将数据作为表单参数从客户端发送到服务器。如果这样做,您将不得不手动将其转换回一个对象以插入到 mongodb。如果您只是将其作为 json 字符串发送,这样您就不必在服务器端进行转换。

data: JSON.stringify(data),
contentType: 'application/json'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多