Reputation: 31
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.
Upvotes: 0
Views: 271
Reputation: 1074495
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);
}
});
Upvotes: 3