繁体   English   中英

req.body 中的 JSON 数据数组

[英]JSON data array in req.body

所以我试图将 json 数据传递给我的req.body

数据如下所示:

answers = ["A","B"]; //This is an array that will be added to the JSON Object

var Student_Answers = { //This is the JSON object
   Answers: answers,
   matricNumber: matric
};

这是帖子请求:

$.ajax({
      type: "POST",
      url: `/exam/${matric2}`,
      dataType: "json",
      data: Student_Answers,
      success: function(data) {
        console.log("data received: ", data);
      }
    });

所以数据成功传递给req.body但我的问题是数据在req.body输出中的req.body ,当我记录req.body它看起来像这样:

 {
  'Answers[]': [ 'A', 'B' ],
  matricNumber: '88/2386'
}

但我所期待的

 {
  Answers: [ 'A', 'B' ],
  matricNumber: '88/2386'
}

有人可以向我解释为什么在req.body ('Answers[]': [ 'A', 'B' ])中以这种方式查看答案数组。它搞砸了我将数据保存到 mongodb 的过程。

dataType告诉jQuery的那种你希望在响应返回的数据是什么。 要告诉 jQuery 您在请求中发送的数据类型,请设置contentType (是的,这混淆的是data是发送数据,但dataType是你期望的响应类型API失败😊。)您还需要自己字符串化它,jQuery将不会为你做:

$.ajax({
  type: "POST",
  url: `/exam/${matric2}`,
  contentType: "application/json",       // <===========
  data: JSON.stringify(Student_Answers), // <===========
  success: function(data) {
    console.log("data received: ", data);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM