简体   繁体   中英

JSON data array in req.body

So I am trying to pass json data to my 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:

 {
  '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.

dataType tells jQuery what kind of data you're expecting back in the response. To tell jQuery what kind of data you're sending in the request, set 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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