0

I have been trying to send an array of objects inside a form data using React JS at the backend. When I am pushing the data inside form data using its append method, it is showing my array as this

SurveyAnswers: [object object, object, object]

in browsers network tab but we have been receiving null at the backend. We have checked the backend API it is working fine when we are sending data using postman, But, when data is being sent through frontend, it is having a problem. Following is my code snippet:

const answers = [ 
  {
    Answer: "Hello World",
    QuestionId: 26,
    UserId: 190
  },
  {
    Answer: "Document",
    File: file,
    UserId: 190,
    QuestionId: 23
  }
]

const onSubmit = () => {
  const data = new FormData();
  data.append("SurveyAnswers", answers);
  const res = await executeAddSurveyFormAnswers({ data: data });     
  console.log('response, res);
}

2 Answers 2

2

If you're trying to pass an object, you will need to "stringify" the object

data.append("SurveyAnswers", JSON.stringify(answers))

Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object. I don't know what language you are using for server side, but you can do a search for "parse json string in XXX" <-XXX is the language (ie.. C#)

Sign up to request clarification or add additional context in comments.

1 Comment

We are using .net 5.0 framework on backend and using a DTO. The API is working fine when running on Postman while sending data like this. SurveyAnswerDtos[0].Answer: SurveyAnswerDtos[0].DiagnosticId:203 SurveyAnswerDtos[0].CustomerUserId:d9d9b0de-b069-4d7c-a14a-6224d2bade30 SurveyAnswerDtos[0].InquiryId:113 Can you please verify the solution after this?
0

Then on the backend, you will need to "Parse" or "Deserialize" the string to convert back to an object.

If you're using Node.js, you'd use JSON.parse() in order to deserialize the stringified object to a native javascript object.

2 Comments

What if I am using Asp Dot Net Core 5.0 framework? How can I deserialize it at the backend?
In order to deserialize using c#, you need to use the respective namespaces in order to get access to the 'JsonSerializer-class provided by System.Text.Json. For a comprehensive guide about (de-)serializing, please see here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.