0

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.

1

1 Answer 1

3

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);
  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

when i do that it just passes { } to the req.body
@leonardikeh - The above will definitely pass JSON for Student_Answers to the server. You probably need to reseach body parsing on Express (it's not automatic, see the ``body-parser` package](npmjs.com/package/body-parser)). But your question was about the client side of this; once you've had a go at the server side of it, if you're still stuck after doing your research, etc., post a question showing an minimal reproducible example of your server-side handling of the JSON and we can help.
thank you very much, this helped a lot [link](npmjs.com/package/body-parser), i was using urlencodedParser instead of jsonParser to parse the data.
@leonardikeh - Nice one solving it! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.