Getting data as null at the backend when sending an array of objects using formdata in React JS

Viewed 488

I want to send an array of objects inside formdata in React JS. When I am appending data inside formdata, it is being received as null at the backend and the API is returning me 500 internal server error. I have tried some of the solutions from the internet but not much support was found. The ways that I have tried till yet are mentioned below:

const surveyFormAnswers = [{Answer: "Hello", QuestionId: 1}, {Answer: "Document", QuestionId: 2, File: file (object)];

const data = new FormData();
data.append('SurveyFormAnswersDtos', JSON.stringify(surveyFormAnswers));
await executeAddSurveyFormAnswers({data: data});

In this case, I am sending a stringified array at the backend (I can see my array being sent inside the browser's Network tab), but at backend, we are using dotnet core5.0. We do not know how exactly can we deseriliaze or parse our request data.

In the second approach, I am appending my data manually inside the formdata (got this approach from the internet) but this is also sending me 500 internal server error from the backend. My code in this case looks like below:

const data = new FormData();
for (var i = 0, valuePair; (valuePair = surveyFormAnswers[i]); i++)
  for (var j in valuePair) data.append(j, valuePair[j]);
await executeAddSurveyFormAnswers({data: data});

I am also attaching a postman screenshot so that you can check the required format of data to be sent

Click on the link below to see data being sent using postman

I have been using customized hook for axios and the definition for AddSurveyFormAnswers is below:

export function AddSurveyFormAnswersUrl(token) {
  return {
    url: `/SurveyAnswer/AddSurveyAnswers`,
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      ContentType:
        "multipart/form-data; boundary=<calculated when request is sent>",
    },
  };
}
0 Answers
Related