简体   繁体   English

req.body 中的 JSON 数据数组

[英]JSON data array in req.body

So I am trying to pass json data to my req.body所以我试图将 json 数据传递给我的req.body

The data looks like this:数据如下所示:

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

This is the post request:这是帖子请求:

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

So the data got passed to the req.body successfully but my problem is how the data looks like in the req.body output, when I logged the req.body it looks like this:所以数据成功传递给req.body但我的问题是数据在req.body输出中的req.body ,当我记录req.body它看起来像这样:

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

But what I am expecting但我所期待的

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

Can someone explain to me why the answers array is viewed that way in the req.body ('Answers[]': [ 'A', 'B' ]) .it is messing up my saving the data to mongodb.有人可以向我解释为什么在req.body ('Answers[]': [ 'A', 'B' ])中以这种方式查看答案数组。它搞砸了我将数据保存到 mongodb 的过程。

dataType tells jQuery what kind of data you're expecting back in the response. dataType告诉jQuery的那种你希望在响应返回的数据是什么。 To tell jQuery what kind of data you're sending in the request, set contentType .要告诉 jQuery 您在请求中发送的数据类型,请设置contentType (And yes, it is confusing that data is the data to send, but dataType is the type of response you expect. API fail. 😊 ) You also need to stringify it yourself, jQuery won't do it for you: (是的,这混淆的是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